我需要将一些数据写入子文件句柄。文件句柄是在分叉之前在父级中创建的。这是因为我可以从父级的文件句柄中读取数据,因为 fork 保留文件句柄并锁定它们(如果有的话),在父级和子级之间共享。这是为了在 linux 和 windows 平台上共享父子节点的数据。我能够在 linux 中使用 IPC::Shareable 进行数据共享,但由于 windows 中的 semaphore.pm 不可用,这在 windows 中不起作用 [windos 不支持 semaphore.pm],因此对于 windows,我尝试了 Win32::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>;
}