how to kill a spawned process when it hangs

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I run a perl script in which I call an interactive process which is
automated via a HERE document. But if something goes wrong with the
called process, say password has changed and my perl script is passing
the old, now-wrong password, it gets stuck and sort-of hangs. I would
like my code to address this situation. Smooth execution of the process
normally takes less than a second, at worst it could take 15 seconds. I
would like to add a while loop which keeps checking after a two-second
pause whether the called process has terminated. If it is still running
after 15 seconds, I would like to kill it.

Sample HERE-document (a shell-script named : exec_this.tmp) contents :
call_app << TO_HERE

Perl Code (untested, to give the reader an idea of the flow) :

use strict ;
`my_dir/exec_this.tmp`  ;  # (I may want to capture the pid of the
exec_this.tmp proc
    # started via these back-tics. There are other ways to guess the
pid with
    # reasonable accuracy, but capturing it would be fool-proof.)
# How to capture pid of the process started from within those
# Please advise.
my $time_count = 0;
while (1)  {
    sleep 2 ;
    $time_count = $time_count + 2;
    if PID/PROC combo no longer active  { last ; } ;
    if( $time_count > 15 )  {
        ` kill -9 PID ` ;
        last ;

How to read PID of the process started from within the backticks,
Please help. Thanks in advance.

Re: how to kill a spawned process when it hangs

[ no shell here. F'ups trimmed ]

Quoted text here. Click to load it

So you want to implement a timeout for the external program?

That Question is Asked Frequently:

   perldoc -q timeout

       How do I timeout a slow event?

Quoted text here. Click to load it

Then backticks are not the Right Tool.

You  use backticks when you want to capture the _output_ of
the external program.

Quoted text here. Click to load it

You should not shell-out for things that are easily done in native Perl:

   perldoc -f kill

(and you should try "nicer" ways to kill before resorting to -9.)

Quoted text here. Click to load it

Use a "pipe open" to run the external program rather than backticks:

   perldoc -f open


      Open returns nonzero upon success, the undefined value other-
      wise.  If the "open" involved a pipe, the return value happens
      to be the pid of the subprocess.

    Tad McClellan                          SGML consulting                   Perl programming
    Fort Worth, Texas

Site Timeline