Run a command, but kill it if it has not returned after a specified timeout
Run an arbitrary command, with a specific timeout in seconds. If the command completes inside the timeout,
the exit status is that of the command. If the timeout interval expires, the command is
killed and the script exits with status 127. The motivation is to prevent a flakey program which occasionally
hangs from stopping a long running procedure which could otherwise continue.
Usage: run-with-timeout seconds command
[optional arguments to command]
Notes
This script starts a backgrounded subshell which sleeps for the timeout period,
and then sends a SIGALRM to its parent.
The main script sets a trap on SIGALRM, with a handler function to kill (SIGTERM) the saved PID of the
named command.
The named command is also run in background, with the PID saved, and then
the parent script waits for the command to complete.
If it completes normally, the alarm subshell
is killed and the script exits. If the command hangs, the alarm subshell
will eventally time out (finish sleeping) and send SIGALRM to the parent, which will then kill the command.
Tested on Linux and OSX 10.4 with ksh
2008/07/05 Richard Brittain, Dartmouth College Computing Services.
Richard's Software Page
Richard Brittain