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:

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"; } }
Updated so that is should work now. Here is the full version I used for testing:
#!/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
Hope that helps.

        - tye (but my friends call me "Tye")

In reply to (tye)Re: fork n wait by tye
in thread fork n wait by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.