Passing data from child to parent after exec in Perl

I would like to call the perl program child.pl in another perl program parent.pl and hope to transfer the data from child.pl to parent.pl and print this data with parent.pl . system("perl child.pl") may not work, because parent.pl will not do anything until child.pl completes. I read the perlipc online doc , it seems that pipe() and fork() may meet some of my needs, but I was unable to find a method to pass data from the child process to parents after exec . Here's the parent.pl code:

 #!/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"; 
+4
source share
1 answer

This may be useful:

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

public function, from perldoc :

For three or more arguments, if MODE is | -, the file name is interpreted as the command for which the output should be sent, and if MODE is - | , the file name is interpreted as a command that outputs the output to us.

If you don't want to touch stdout, you need cooperation with a child, and then you can use named pipes:

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, $fpath, O_WRONLY) or die "sysopen: $!"; print "screen hello\n"; print $fifo "parent hello\n"; close($fifo); 
+7
source

Source: https://habr.com/ru/post/1468893/


All Articles