I have a perl program which forks children and does some processing depending on how each child exits. I keep the exited child's pid and return code in a hash to process later:

$SIG{CHLD} = \&waitforchildren; # reaper: sub waitforchildren { my $cpid; while ( ($cpid = waitpid(-1, &WNOHANG)) > 0 ) { $TrappedPIDs{$cpid} = WEXITSTATUS($?) if WIFEXITED($?); } } # processing routine ... foreach $pid ( keys(%TrappedPIDs) ) { # check return code for pid and do something }

My program can only trap some of the children exited. Some others exit, but never detected by my foreach loop. So my program thinks that they are still running. So I modified the reaper routine to print all trapped PIDs of exited children:

sub waitforchildren { my $cpid; my $pidlist = " "; + while ( ($cpid = waitpid(-1, &WNOHANG)) > 0 ) { $TrappedPIDs{$cpid} = WEXITSTATUS($?) if WIFEXITED($?); } foreach $cpid ( keys(%TrappedPIDs) ) { + $pidlist .= " ".$cpid; } print " TRAPPED PIDS: $pidlist \n"; }

This printed the following:

TRAPPED PIDS: 20090 19934
TRAPPED PIDS: 20090 19934 16465
TRAPPED PIDS: 20090 19934 20091 16465
TRAPPED PIDS: 20092

I also added a print command to my processing routine. It only checks 20092! So it seems that hash %TrappedPIDs ended up having just one PID despite the fact that the reaper routine caught more PIDs and added them to the hash! I understand that reaper routine itself can be interrupted with the signals of children which died around the same time. However, this should not destroy the elements of the hash. What am I doing wrong here?


In reply to hash elements are lost during reaping by umitd

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.