Perl无法写入子进程中的文件句柄
发布时间:2020-12-15 21:45:44 所属栏目:大数据 来源:网络整理
导读:我需要将一些数据写入child中的文件句柄.文件句柄是在分叉之前在父级中创建的.这是因为我可以从父文件句柄中读取数据,因为fork保留文件句柄并锁定它们(如果有的话),在父和子之间共享.这是在 Linux和Windows平台上共享父和子的数据.我能够在Linux中使用IPC ::
我需要将一些数据写入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 filen"; 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 writen"; open FH,">>testfile.txt" or die "cant open file: $!n"; print FH "dummy datan"; print FH "dummy datan"; print "child sleeping for 5 sec before exitingn"; sleep 50; exit; } else { print "entering the parent processn"; open FH,"<testfile.txt" or die "cant open file: $!n"; print <FH>; print <FH>; } 解决方法
父进程应至少等待一小段时间才能允许孩子写一些时间.
use strict; use warnings; print "creating filen"; 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 writen"; open my $FH,">>","testfile.txt" or die "cant open file: $!n"; print $FH "dummy datan"; print $FH "dummy datan"; # print "child sleeping for 5 sec before exitingn"; # sleep 50; exit; } else { sleep 1; print "entering the parent processn"; 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |