use strict; use warnings; my @ips = (1 .. 10); my %pipe; for my $ip (@ips) { pipe my $reader, my $writer; my $pid = fork; die "Error: failed to fork\n" if not defined $pid; if ($pid) { close $writer; $pipe{$ip} = $reader; } else { sleep $ip; print $writer 365*$ip; exit; } } my @nums; for my $ip (@ips) { my $handle = $pipe{$ip}; # Necessary to avoid glob mapping push @nums, <$handle>; } 1 while (wait != -1); print "Numbers: @nums \n";
Note that since reading is a blocking operation, it can't happen in the normal flow. You also need to wait to reap until after the output channels have been read. Unfortunately, I've missed spec with the code above, because I've removed the maximum number of children constraint. This one is problematic, since it requires that you be able to poll your children to find out if anyone is ready to output and be reaped. You can't just call wait, since your children won't be ready for reaping until they are done with their I/O.
At this point, you have two choices. You can use flock and have each child write asynchronously to an output channel. This choice is nice, because then you can do your reaping in a manner similar to how you were working before:
if ( $children == $max ) { wait(); }
Alternatively, you can use IO::Select (CORE, though select works if you are self-destructive) to check your handles if they are ready to be read, and reap as you go. You could also implement something simpler here with threads, allowing you to bypass the need for pipes.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
In reply to Re: Correct usage of fork and pipe?
by kennethk
in thread Correct usage of fork and pipe?
by CircusGimp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |