Felix2000 has asked for the wisdom of the Perl Monks concerning the following question:

So I've been away from perl for a long time, now I have the chance to get back and I'm jumping all in. But to the problem, I've been playing with a program to test some equipment and essentially it'll fork a bunch of children and have them do a task eg. check a webpage. The parent process writes the webpage url for the child to check. This I all have working fine based on some examples from Proc::Fork. What I'm having alot of trouble with is getting the children to reply back to the parent so that I can aggregate stats and such. I have a feeling I'm not reading from the pipes properly.
I've boiled down the code to the basics. I've commented out the parts that I believe are wrong.
#!/usr/bin/perl use strict; use Proc::Fork; use IO::Pipe; my $num_children = shift; # How many children we'll create my %children; # Store connections to them my %childrenin; # Store connections from children $SIG{CHLD} = 'IGNORE'; # Don't worry about reaping zombies # Spawn off some children for my $num ( 1 .. $num_children ) { # Create a pipe for parent-child communication my $pipe = IO::Pipe->new; my $pipein = IO::Pipe->new; # Child simply echoes data it receives, until EOF run_fork { child { print "[$num] Child Start\n"; $pipe->reader; $pipein->writer; my $data; my $dataout = $pipein; while ($data = <$pipe>) { chomp($data); print STDERR "Child [$num]: $data \n"; print $dataout "[$num]: $data \n"; } exit; } }; # Parent here $pipe->writer; $children{$num} = $pipe; $pipein->reader; $childrenin{$num} = $pipein; } # Send some data to the kids for my $i ( 1 .. $num_children ) { my $child = $children{$i}; print $child "Line 1\n"; } # Read data from children # this is where I believe I'm going wrong. =comment for my $i ( 1 .. $num_children ) { my $childin = $childrenin{$i}; my $datain; while ( $datain = <$childin> ) { print "[Parent] $datain \n";; } } =cut

Replies are listed 'Best First'.
Re: When forking how can the child talk back to the parent?
by merlyn (Sage) on Jan 29, 2009 at 22:22 UTC
Re: When forking how can the child talk back to the parent?
by targetsmart (Curate) on Jan 30, 2009 at 18:50 UTC
    You can also try IPC::Msg (message queues) or IPC::SharedMem (shared memory) which would help two process to communicate, (but pipes must be more effective and simple to use I believe).

    Vivek
    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.