how to kill a spawned process when it hangs

D

dn_perl

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 ;
}
}

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

Tad McClellan

[ 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?

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

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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top