我需要将一些数据写入 child 中的文件句柄。文件句柄是在 fork 之前在父级中创建的。这是因为我可以从父文件句柄中读取数据,因为 fork 保留文件句柄并锁定它们(如果有的话),在父子之间共享。这是为了在 linux 和 windows 平台上共享父子进程中的数据。我能够在 linux 中使用 IPC::Shareable 进行数据共享,由于 windows 中 semaphore.pm 不可用 [windos 不支持 semaphore.pm],这在 windows 中不起作用,所以对于 windows,我尝试了 Win32::MMF正在崩溃我的 perl 编译器。
因此,使用文件句柄方法,IO 写入不会在 child 中发生。请查看下面的代码
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>;
}
最佳答案
父进程应该至少等待几分之一秒,让子进程有时间进行写入。
use strict;
use warnings;
print "creating file\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 my $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 {
sleep 1;
print "entering the parent process\n";
open my $FH, "<", "testfile.txt" or die "cant open file: $!\n";
print while <$FH>;
}
输出
creating file
entering in to child and opening file for write
entering the parent process
dummy data
dummy data
关于Perl 无法写入子进程中的文件句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19809999/