I have a script that launches various external processes to perform tasks in a 3rd party software product. Unfortunately, these tasks will sometimes hang, and so the entire script will hang.

This is running in Perl 5.6 on AIX, and I am not permitted to install any additional modules. The solution I have come up with is shown below.

This seems to work OK, but I would like to know if there is a more clever way to do this. Also, this code doesn't cope well if the spawned process completes within the time limit. I'm guessing I should be able to use waitpid() to check see if the child has completed running; is that a sensible way to do it?

One final thing to note is that I need to work with any output returned from the spawned process. At present I am using code such as this:

my $rc = `/usr/bin/somecommand param1 param2`;

How might I get this output back into the parent process?

#!/usr/bin/perl -w use strict; if (!defined(my $pid = fork)) { print "Failed to fork.\n"; exit -1; } else { if ($pid == 0) { print "PID variable is zero; I am the child.\n"; # This is where we would execute the external process # Replaced this with a sleep loop to simulate a long-running p +rocess for (my $x = 0; $x < 10; $x++) { print "Sleeping iteration $x.\n"; sleep 1; } print "Child process has finished.\n"; exit 0; } else { print "I am the parent. Child PID is $pid.\n"; my $timer = 0; while ($timer < 5) { sleep 1; $timer++; } # After 5 seconds, kill the child print "Killing the child process.\n"; kill 1, $pid; print "Parent process finishing.\n"; } } print "End of the forked code block.\n";

In reply to Launching an external process with a run-time limit by TheFluffyOne

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.