how to kill a spawned process when it hangs

how to kill a spawned process when it hangs

Post by dn_p.. » Thu, 05 May 2005 19:10:50



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
username
password
option_number
more_inputs
TO_HERE

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

#!/bin/perl
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
back-ticks?
# 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 ;
    }

Quote:}

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

how to kill a spawned process when it hangs

Post by Tad McClella » Thu, 05 May 2005 21:55:21


[ no shell here. F'ups trimmed ]


> 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.

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?

Quote:> `my_dir/exec_this.tmp`  ;  # (I may want to capture the pid of the

Then backticks are not the Right Tool.

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

Quote:>         ` kill -9 PID ` ;

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.)

Quote:> How to read PID of the process started from within the backticks,
> though?

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

    Fort Worth, Texas