I trying to write a script with the following goals:
  • create child processes
  • under normal situation, wait for all child process to finish
  • but when ctrl-c is pressed, I want it to show how many children are still running

    Below is the script that I currently have. The problem is that it does not work. Without even pressing ctrl-c, sometimes it tells me that some kids finished, and sometimes it does not.
    #!/usr/bin/perl use strict; use POSIX qw(:signal_h :errno_h :sys_wait_h); $SIG{CHLD} = \&REAPER; my (@all_kids, @dead_kids); my @array = qw(a b c d e f g h); for (1 .. 10) { my $pid = fork(); if ($pid) { push (@all_kids, $pid); } elsif ($pid == 0) { print "@array\n\n"; sleep 5; exit (0); } else { die "Could not fork: $!\n"; } print "Running another child process - $pid.\n"; } print "All child processes have been ran.\n"; print "@all_kids\n"; $SIG{INT} = \&tsktsk; foreach (@all_kids) { waitpid ($_, 0); } print "All child processes are finished.\n"; sub tsktsk { print "Ctrl-C Trap\n"; my %alive_kids; for my $i (@all_kids, @dead_kids) { $alive_kids{$i}++; } for (sort keys %alive_kids) { print "$_\n" if ( $alive_kids{$_} == 1 ); } exit; } sub REAPER { my $pid; $pid = waitpid(-1, &WNOHANG); if ($pid == -1) { } elsif ( WIFEXITED($?) ) { print "Process $pid exited.\n"; push( @dead_kids, $pid ) } else { print "False alarm on $pid.\n"; } $SIG{CHLD} = \&REAPER; }

    In reply to Monitoring Child Process 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.