我需要将一些数据写入子文件句柄中。文件句柄是在分叉之前在父文件中创建的。这是因为我可以从父文件句柄中读取数据,因为福克保留文件句柄和锁(如果有的话),在父和子之间共享。这是为了共享在linux和windows平台上工作的父级和子级的数据。我能够在linux中使用IPC::Shareable进行数据共享,这在windows中是行不通的,因为windows中的semaphore.pm不支持semaphore.pm,所以对于windows,我尝试了Win32 32::MMF,它破坏了我的perl编译器。
因此,使用文件句柄方法,IO写入不会发生在子程序中。请查看下面的代码
use strict;
use warnings;
print "creating file\n";
open FH, ">testfile.txt" or die "cant open file: $!\n";
close FH;
my $pid = fork();
if ( $pid == 0 )
{
print "entering in to child and opening file for write\n";
open FH, ">>testfile.txt" or die "cant open file: $!\n";
print FH "dummy data\n";
print FH "dummy data\n";
print "child sleeping for 5 sec before exiting\n";
sleep 50;
exit;
}
else
{
print "entering the parent process\n";
open FH, "<testfile.txt" or die "cant open file: $!\n";
print <FH>;
print <FH>;
}发布于 2013-11-07 06:47:41
谢谢你帮我解决这个问题。昨天我试图解决这个问题,并在使用它与文件句柄一起在子和父级之间共享数据时发现了一件有趣的事情,即我们可以用下面的代码解决这个问题,诀窍是打开文件句柄之前和里面的文件句柄,只需写到文件句柄,而不需要重新打开它。以下是修改后的代码。
use strict;
use warnings;
use Fcntl qw(:flock SEEK_END);
print "creating file handle\n";
open my $FH, ">testfile.txt" or die "cant open file: $!\n";
#close FH;
my $pid = fork();
if ( $pid == 0 )
{
print "entering in to child and opening file for write\n";
#open FH, ">>testfile.txt" or die "cant open file: $!\n";
# Put a exclusive lock in the filehandle for dening access to any other process during this child process run
flock($FH, LOCK_EX) or die "Cannot lock testfile.txt - $!\n";
# and, in case someone appended while we were waiting...
seek($FH, 0, SEEK_END) or die "Cannot seek - $!\n";
# write data to temp file with exclusive lock on it
print $FH "dummy data\n";
print $FH "dummy data\n";
# remove the lock once writing is done
flock($FH, LOCK_UN) or die "Cannot unlock temp.txt - $!\n";
print "child sleeping for 5 sec before exiting\n";
sleep 2;
exit;
}
else
{
print "entering the parent process\n";
#flock(FH, LOCK_UN) or die "Cannot unlock temp.txt - $!\n";
sleep 3;
open $FH, "<testfile.txt" or die "cant open file: $!\n";
while (<$FH>){
print "$_\n";
}
}https://stackoverflow.com/questions/19809999
复制相似问题