加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Perl中的exec之后将数据从子节点传递给父节点

发布时间:2020-12-16 06:18:54 所属栏目:大数据 来源:网络整理
导读:我想在另一个perl程序parent.pl中调用perl程序child.pl,并希望将数据从child.pl传递给parent.pl并通过parent.pl打印这些数据. system(“perl child.pl”)可能不起作用,因为parent.pl在child.pl完成之前不会执行任何操作.我读了 the online doc of perlipc,似
我想在另一个perl程序parent.pl中调用perl程序child.pl,并希望将数据从child.pl传递给parent.pl并通过parent.pl打印这些数据. system(“perl child.pl”)可能不起作用,因为parent.pl在child.pl完成之前不会执行任何操作.我读了 the online doc of perlipc,似乎pipe()和fork()可以匹配我的一些需求,但是我没能找到一个方法在exec之后将数据从子进程传递给父进程.这是parent.pl的代码:

#!/usr/bin/perl -w

pipe(FROM_CHILD,TO_PARENT);  

$pid = fork();  

if ($pid == 0) {  
    # We're in the child process.  
    close(FROM_CHILD);  
    # Send data to parent.  
    print TO_PARENT "Hello,parentn"; #  I can pass data to parent before exec
    exec("perl child.pl");             #  But how what should I do after exec,in child.pl?
    exit(0);  # Terminate child.  
} 
elsif (undef $pid) {  
    print "Not defined: means an error.";  
} 
else {  
    # Parent process.  
    close(TO_PARENT);  
    $data = <FROM_CHILD>;  
    print "From child: $datan";  
    $id = wait();  
    print "Child $id is dead.n";

解决方法

这可能会有所帮助:

#!/usr/bin/perl
open (my $child,"-|","./child.pl") or die("$!");
while (<$child>) {
  print "P: $_";
}
close($child);

开放功能,from perldoc:

For three or more arguments if MODE is |-,the filename is
interpreted as a command to which output is to be piped,and if MODE
is -|
,the filename is interpreted as a command that pipes output to
us.

如果您不想触摸标准输出,那么您需要孩子的合作,然后您可以使用命名管道:

parent.pl

#!/usr/bin/perl
use strict;
use warnings;
use Fcntl;
use POSIX;
my $fpath = '.named.pipe';

mkfifo($fpath,0666) or die "mknod $!";
system("perl child.pl &");
sysopen(my $fifo,$fpath,O_RDONLY) or die "sysopen: $!";

while (<$fifo>) {
  print "P: $_";
}
close($fifo);
unlink($fifo);

child.pl

#!/usr/bin/perl
use strict;
use warnings;
use Fcntl;
use POSIX;

my $fpath = '.named.pipe';
sysopen(my $fifo,O_WRONLY) or die "sysopen: $!";
print "screen hellon";
print $fifo "parent hellon";
close($fifo);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读