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

dear gr8 11, I mostly stole the following code:
#!/usr/bin/perl -w # pipe2 - use pipe and fork so child can send to parent use IO::Handle; pipe(READER, WRITER); WRITER->autoflush(1); if ($pid{vmstat} = fork()){ print "Parent from vmstat\n"; close WRITER; while (<READER>){ chomp $_; print "Parent Pid $$ just read this: `$_'\n"; } } else { die "cannot fork: $!" unless defined $pid{vmstat}; close READER; open IN, "vmstat 5 5|"; while (<IN>){ chomp $_; print WRITER "Child Pid vmstat $$ is sending this --->$_<--- +\n"; } close WRITER; # this will happen anyway exit; } waitpid($pid{vmstat},0); close READER; pipe(READER, WRITER); WRITER->autoflush(1); if ($pid{iostat} = fork()){ print "Parent from iostat\n"; close WRITER; while (<READER>){ chomp $_; print "Parent Pid $$ just read this: `$_'\n"; } } else { die "cannot fork: $!" unless defined $pid{iostat}; close READER; open IN, "iostat 5 5|"; while (<IN>){ chomp $_; print WRITER "Child Pid iostat $$ is sending this --->$_<--- +\n"; } close WRITER; # this will happen anyway exit; } waitpid($pid{iostat},0); close READER;
but I can't see how I would get iostat and vmstat to run in parallel, both writting to WRITER so that the parent process can get the data. How can I spawn several process to run in parallel yet still write their data back to a parent PID? thanks ohhhh so much, me

Replies are listed 'Best First'.
Re: multiple forks running in parallel yet still getting their data
by Fletch (Bishop) on May 14, 2004 at 04:06 UTC

    You really would need a pair of pipes for each child and to use select to determine which has output ready for reading. See perldoc perlipc and perldoc IO::Select, or perhaps IPC::Run. Or better yet, use POE!.