ipc - Passing data from child to parent after exec in Perl -


i call perl program child.pl in perl program parent.pl, , hope pass data child.pl parent.pl , print these data parent.pl. system("perl child.pl") may not work, since parent.pl nothing until child.pl completes. read the online doc of perlipc, seems pipe() , fork() match of needs, failed find method pass data child process parent after exec. here's code of parent.pl:

#!/usr/bin/perl -w  pipe(from_child, to_parent);    $pid = fork();    if ($pid == 0) {       # we're in child process.       close(from_child);       # send data parent.       print to_parent "hello, parent\n"; #  can pass data parent before exec     exec("perl child.pl");             #  how should after exec, in child.pl?     exit(0);  # terminate child.   }  elsif (undef $pid) {       print "not defined: means error.";   }  else {       # parent process.       close(to_parent);       $data = <from_child>;       print "from child: $data\n";       $id = wait();       print "child $id dead.\n";  

this might helpful:

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

open function, from perldoc:

for 3 or more arguments if mode |- , filename interpreted command output piped, , if mode -| , filename interpreted command pipes output us.

if don't want touch stdout need cooperation child , can use named pipes:

parent.pl

#!/usr/bin/perl use strict; use warnings; use fcntl; use posix; $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;  $fpath = '.named.pipe'; sysopen(my $fifo, $fpath, o_wronly) or die "sysopen: $!"; print "screen hello\n"; print $fifo "parent hello\n"; close($fifo); 

Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -