首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Perl无法在子进程中写入文件句柄。

Perl无法在子进程中写入文件句柄。
EN

Stack Overflow用户
提问于 2013-11-06 10:45:39
回答 3查看 1.9K关注 0票数 5

我需要将一些数据写入子文件句柄中。文件句柄是在分叉之前在父文件中创建的。这是因为我可以从父文件句柄中读取数据,因为福克保留文件句柄和锁(如果有的话),在父和子之间共享。这是为了共享在linux和windows平台上工作的父级和子级的数据。我能够在linux中使用IPC::Shareable进行数据共享,这在windows中是行不通的,因为windows中的semaphore.pm不支持semaphore.pm,所以对于windows,我尝试了Win32 32::MMF,它破坏了我的perl编译器。

因此,使用文件句柄方法,IO写入不会发生在子程序中。请查看下面的代码

代码语言:javascript
运行
复制
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>;


}
EN

Stack Overflow用户

发布于 2013-11-07 06:47:41

谢谢你帮我解决这个问题。昨天我试图解决这个问题,并在使用它与文件句柄一起在子和父级之间共享数据时发现了一件有趣的事情,即我们可以用下面的代码解决这个问题,诀窍是打开文件句柄之前和里面的文件句柄,只需写到文件句柄,而不需要重新打开它。以下是修改后的代码。

代码语言:javascript
运行
复制
use strict;
use warnings;
use Fcntl qw(:flock SEEK_END);

print "creating file handle\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 FH, ">>testfile.txt" or die "cant open file: $!\n";

   # Put a exclusive lock in the filehandle for dening access to any other process   during this child process run
   flock($FH, LOCK_EX) or die "Cannot lock testfile.txt - $!\n";

   # and, in case someone appended while we were waiting...
   seek($FH, 0, SEEK_END) or die "Cannot seek - $!\n";



   # write data to temp file with exclusive lock on it   
    print $FH "dummy data\n";
    print $FH "dummy data\n";

   # remove the lock once writing is done
    flock($FH, LOCK_UN) or die "Cannot unlock temp.txt - $!\n";

 print "child sleeping for 5 sec before exiting\n";
 sleep 2;
 exit;

}
else
{
 print "entering the parent process\n"; 
 #flock(FH, LOCK_UN) or die "Cannot unlock temp.txt - $!\n";

 sleep 3;    
 open $FH, "<testfile.txt" or die "cant open file: $!\n";

 while (<$FH>){
 print "$_\n";
 }
}
票数 2
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19809999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档