I would like to have a parent process spawn a child to perform some task every 5 seconds. I would also like to perform some cleanup every time a child exits.

Unfortunately it appears that sleep exits prematurely when a CHLD signal handler is triggered; for example,

#!/usr/bin/perl use strict; $|++; my $pid = fork(); if ($pid) { # the parent does not exit prematurely when the handler # is set to IGNORE $SIG{CHLD} = sub { print "$$: Reaping a child process in child + signal handler ...\n" }; print "$$: Parent sleeping 5 seconds at [".localtime()."] ...\ +n"; sleep 5; print "$$: That was refreshing. The time is now [".localtime( +)."].\n"; exit(0); } else { print "$$: \tChild sleeping for 2 seconds ...\n"; sleep 2; print "$$: \tChild exiting at [".localtime()."] ...\n"; exit(0); }
results in
3978: Child sleeping for 2 seconds ... 3977: Parent sleeping 5 seconds at [Tue Jan 14 14:17:11 2003] ... 3978: Child exiting at [Tue Jan 14 14:17:13 2003] ... 3977: Reaping a child process in child signal handler ... 3977: That was refreshing. The time is now [Tue Jan 14 14:17:13 2003] +.
From the documentation for sleep, May be interrupted if the process receives a signal such as "SIGALRM".

I can put the sleep in backticks, which seems to work albeit kludgily, but I am annoyed that putting it in backticks will result in a CHLD signal whenever the subprocess exits which means I have to worry about which child it was that exited when the child signal is caught.

My question to the monks is: How would those wiser in the ways of slumber do this?


In reply to Sleeping and reaping by Starky

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.