3 # Execute a command with a timeout
7 # http://www.pixelbeat.org/
9 # Note there is a timeout command packaged with coreutils since v7.0
10 # If the timeout occurs the exit status is 124.
11 # There is an asynchronous (and buggy) equivalent of this
12 # script packaged with bash (under /usr/share/doc/ in my distro),
13 # which I only noticed after writing this.
14 # I noticed later again that there is a C equivalent of this packaged
15 # with satan by Wietse Venema, and copied to forensics by Dan Farmer.
17 # V1.0, Nov 3 2006, Initial release
18 # V1.1, Nov 20 2007, Brad Greenlee <brad@footle.org>
19 # Make more portable by using the 'CHLD'
20 # signal spec rather than 17.
21 # V1.3, Oct 29 2009, Ján Sáreník <jasan@x31.com>
22 # Even though this runs under dash,ksh etc.
23 # it doesn't actually timeout. So enforce bash for now.
24 # Also change exit on timeout from 128 to 124
26 # V2.0, Oct 30 2009, Ján Sáreník <jasan@x31.com>
27 # Rewritten to cover compatibility with other
28 # Bourne shell implementations (pdksh, dash)
30 if [ "$#" -lt "2" ]; then
31 echo "Usage: `basename $0` timeout_in_seconds command" >&2
32 echo "Example: `basename $0` 2 sleep 3 || echo timeout" >&2
38 trap - ALRM #reset handler to default
39 kill -ALRM $a 2>/dev/null #stop timer subshell if running
40 kill $! 2>/dev/null && #kill last job
41 exit 124 #exit with 124 if it was running
51 watchit $1& a=$! #start the timeout
52 shift #first param was timeout for sleep
53 trap "cleanup" ALRM INT #cleanup after timeout
54 "$@"& wait $!; RET=$? #start the job wait for it and save its return value
55 kill -ALRM $a #send ALRM signal to watchit
56 wait $a #wait for watchit to finish cleanup
57 exit $RET #return the value