Perl 无法写入子进程中的文件句柄

标签 perl

我需要将一些数据写入 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/

相关文章:

windows - 在 Windows 上运行 perl 脚本

regex - perl 正则表达式替换非单词字符,除了::

perl - 为什么在这个 Perl 示例中,使用转义字符连接字符串的方式不同?

java - 不同语言中静态代码和有状态代码分离的差异

perl - 同时打印到标准输出和文件

python - Bash 与 Perl/Python : OS call perfomace

Perl 脚本没有运行条件语句?

perl - 在 Ubuntu 14.04 中安装 Tkx perl 模块时遇到问题

Perl strptime 解析毫秒

c++ - 如何在linux下用c/c++构建igmp查询生成器