in reply to fork n wait
Signal handlers in Perl are always a race condition and will probably cause problems after the handler is called enough times. So it is better to ignore SIGCHLD and wait for the children in a different way.
Even if that weren't the case, your signal handler could be called once when two children exit at nearly the same time and you'd end up only waiting for one of those two children.
Also you don't detect when fork() fails.
Here is a stab at it:
Updated so that is should work now. Here is the full version I used for testing:sub subroutine { foreach (1..4) { my $pid= fork; die "Can't fork: $!\n" unless defined $pid; if( ! $pid ) { # do something here exit(0); } } foreach (1..4) { wait(); print "$_ child finished; status is: $?\n"; } }
Hope that helps. - tye (but my friends call me "Tye")#!/s/t/tye/bin/perl -w use strict; subroutine( @ARGV ); exit( 0 ); sub subroutine { local( $| )= 1; foreach (1..4) { my $pid= fork; die "Can't fork: $!\n" unless defined $pid; if( ! $pid ) { sleep( $_[$_-1] ); exit(0); } else { print "Started child $pid...\n"; } } foreach (1..4) { my $pid= wait(); print "$_ child ($pid) finished; status is: $?\n"; } } # Usage: fork4 6 4 8 2
|
|---|