我需要将一些数据写入child中的文件句柄.文件句柄是在分叉之前在父级中创建的.这是因为我可以从父文件句柄中读取数据,因为fork保留文件句柄并锁定它们(如果有的话),在父和子之间共享.这是在Linux和Windows平台上共享父和子的数据.我能够在Linux中使用IPC :: Shareable进行数据共享,这在windows中不起作用,因为windows中没有semaphore.pm [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>;
}
Run Code Online (Sandbox Code Playgroud)
父进程应至少等待几分之一秒,以便给子进程一些时间进行写入。
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>;
}
Run Code Online (Sandbox Code Playgroud)
输出
creating file
entering in to child and opening file for write
entering the parent process
dummy data
dummy data
Run Code Online (Sandbox Code Playgroud)