Link to home
Start Free TrialLog in
Avatar of ilyaz
ilyaz

asked on

Cygwin: How to stop an application after at most a preset amount of time

I am running a large batch job under Cygwin (Win-XP) which is the same application being executed many times with different input data in a for loop. Occasionally, the application hangs. What I want is to automatically interrupt the app if it does finish in predetermined time. One way to do it is something like this:

for ........
do
       my_app ..... &
       sleep 600
       kill -9 $!
done

This will launch the app in background, wait for 600 seconds and then kill it if it hasn't finished by itself. The problem is that even if it does finish by itself, this pass of the loop will still complete only after 600 secs. What I want is for it to finish immediately if the application exits normally and only wait for 600 secs if it does not. How can I do it?

Thanks.
Avatar of Gns
Gns

You can probably do this fine with expect (use a timeout).

-- Glenn
use
pidof my_app ----- to get process id
kill-9 <pid> ----- to kill them
Avatar of ilyaz

ASKER

Glenn,

I found the following expect script on the Web:

#!/usr/bin/expect -f
# run a program for a given amount of time
# i.e. time 20 long_running_program
set timeout [lindex $argv 0]
eval spawn [lrange $argv 1 end]
expect

which I run like this

expect -f timed-run.exp 5 my_app

Although it exits if my_app finishes early, it does not kill my_app if time is up. Is there a simple modification to make it work? Thanks.
Yes, make an expect clause for the timeout with an abort action.
(I'm unable to test out the syntax right now... Check the expect man-page, there is an example on how it might look... Or wait till tomorrow when I have the time:-).

-- Glenn
ASKER CERTIFIED SOLUTION
Avatar of Gns
Gns

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial