I have a script that runs an external command. If the command fails to respond within 20 seconds, I kill it off and proceed to the rest of the script. However, when I have to "kill" the process, it is leaving a zombie child process.

Since this command can be run hundreds to thousands of times in a given period, the zombie processes add up and eventually the system will return with a "Resources not available, unable to fork," and eventually the script will die.

Here is the code in question (which I found using sites like this). Is there a better way to do this, or is my code just screwy.

eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm 20; $CHILD = fork(); if( $CHILD == 0 ) { exec( "my external command" ); } waitpid( $CHILD, 0 ); alarm 0; }; if( $@ ) { die unless $@ eq "alarm\n"; kill 9, $CHILD }

What I need is a way to execute a external command via perl. Have it timout after a certain period if it fails to respond, and then kill the child process if it hits the timeout period.

This is on OS X 10.6 with the latest version of Perl

EDIT: By just simply adding another waitpid after the kill command (as suggested), the zombies are gone. Not sure why I never tried that before! Thanks for the help!


In reply to exec creating zombie processes by jaiieq

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.