in reply to parent wants to capture output from a spawned child

If you fork by way of magical open the kids can print their messages and you can read them on the filehandle:

#!/usr/bin/perl -w use strict; my %kids = (); my @msgs = (); $SIG{CHLD} = q/IGNORE/; for ( 'a', 'b', 3) { my ( $pid, $fh); defined($pid = open $fh, "-|") or warn $! and last; if ($pid) { # be parental $kids{$pid} = $fh; next; } else { kid_code($_); } } push @msgs, <$_> for values %kids; print @msgs; sub kid_code { # do childish things, then (goes to $fh in parent) print "$_[0]. Your Message Here$/"; exit(0); }
IO:Select would improve this. You might also look at Parallel::ForkManager.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: parent wants to capture output from a spawned child
by perlknight (Pilgrim) on Nov 26, 2001 at 01:04 UTC
    Thanks for the help, I ended up using "open" instead of "pipe" because pipe was slower (not sure if I am doing something wrong with it). Quick follow up question? I notice "push @msgs, <$_> for values %kids" deference the filehandle where as something like: " for (values %kids) { print "<$_>\n"; }" returns a ref. Is my assumption correct?

      Nearly right. In push @msgs, <$_> for values %kids; the diamond operator is evaluated in list context, giving you all messages. In print "<$_>\n"; the diamond is not evaluated inside double quotes. Instead, you get literal '<' followed by the interpolated $_, then literal '>'. $_ is a filehandle, a stringified ref to a typeglob is printed. You can do what I think you want with print "@{[<$_>]}\n"; or just print <$_>;

      After Compline,
      Zaxo