Here's a way to reap your children, reaping as soon as they're gone, and without reaping any other child processes. It uses the fact sleep gets interrupted on a signal:
#!/usr/bin/perl use 5.010; use strict; use warnings; use autodie; use POSIX ':sys_wait_h'; $SIG{CHLD} = sub {1;}; my $start = time; my %children; foreach (1 .. 10) { if (my $pid = fork) { $children{$pid} = 1; } else { my $diff = time - $start; say "$diff: Child $$"; sleep rand 10; $diff = time - $start; say "$diff: Child $$ out of here"; exit; } } while (1) { foreach my $pid (keys %children) { if (my $r = waitpid($pid, WNOHANG)) { delete $children{$pid}; my $diff = time - $start; say $r == $pid ? "$diff: Reaped $pid" : "$diff: $pid gone! +"; } } last unless %children; my $diff = time - $start; say "$diff: Sleeping"; sleep 1; } my $diff = time - $start; say "$diff: End"; __END__ 0: Child 3975 0: Child 3976 0: Child 3976 out of here 0: Child 3977 0: Child 3978 0: Child 3979 0: Child 3980 0: Child 3981 0: Child 3982 0: Child 3983 0: Child 3984 0: Reaped 3976 0: Sleeping 1: Child 3977 out of here 1: Reaped 3977 1: Sleeping 2: Child 3979 out of here 2: Child 3980 out of here 2: Reaped 3979 2: Sleeping 2: Reaped 3980 2: Sleeping 3: Child 3982 out of here 3: Reaped 3982 3: Sleeping 4: Child 3978 out of here 4: Reaped 3978 4: Sleeping 4: Child 3981 out of here 4: Reaped 3981 4: Sleeping 4: Child 3984 out of here 4: Reaped 3984 4: Sleeping 5: Child 3983 out of here 5: Reaped 3983 5: Sleeping 8: Child 3975 out of here 8: Reaped 3975 8: End

In reply to Re: subroutines which forks? by JavaFan
in thread subroutines which forks? 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.