TheFluffyOne has asked for the wisdom of the Perl Monks concerning the following question:
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";
|
|---|