Release 4.0.0-preview1-00184
[platform/core/csapi/tizenfx.git] / tools / timeout.sh
1 #!/bin/sh
2
3 # Execute a command with a timeout
4
5 # License: LGPLv2
6 # Author:
7 #    http://www.pixelbeat.org/
8 # Notes:
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.
16 # Changes:
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
25 #                       to match coreutils.
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)
29
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
33     exit 1
34 fi
35
36 cleanup()
37 {
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
42 }
43
44 watchit()
45 {
46     trap "cleanup" ALRM
47     sleep $1& wait
48     kill -ALRM $$
49 }
50
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
58