我想在另一个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,parent\n"; # 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: $data\n"; $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 hello\n"; print $fifo "parent hello\n"; close($fifo);