-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdtimeout
executable file
·77 lines (64 loc) · 1.99 KB
/
cmdtimeout
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/bin/bash
#
# Based on
# http://www.bashcookbook.com/bashinfo/source/bash-4.0/examples/scripts/timeout3
# with modifications from
# http://stackoverflow.com/questions/5719030/bash-silently-kill-background-function-process
#
# The Bash shell script executes a command with a time-out.
# Upon time-out expiration SIGTERM (15) is sent to the process. If the signal
# is blocked, then the subsequent SIGKILL (9) terminates it.
#
# Based on the Bash documentation example.
#
# Hello Chet,
# please find attached a "little easier" :-) to comprehend
# time-out example. If you find it suitable, feel free to include
# anywhere: the very same logic as in the original examples/scripts, a
# little more transparent implementation to my taste.
#
# Dmitry V Golovashkin <Dmitry.Golovashkin@sas.com>
scriptName="${0##*/}"
declare -i DEFAULT_TIMEOUT=9
# Timeout.
declare -i timeout=DEFAULT_TIMEOUT
# Interval between checks if the process is still alive.
declare -i interval=1
function printUsage() {
cat <<EOF
Synopsis
$scriptName [-t timeout] command
Execute a command with a time-out.
Upon time-out expiration SIGKILL (9) is sent to the process.
-t timeout
Number of seconds to wait for command completion.
Default value: $DEFAULT_TIMEOUT seconds.
As of today, Bash does not support floating point arithmetic (sleep does),
therefore all time values must be integers.
EOF
}
# Options.
while getopts ":t:i:" option; do
case "$option" in
t) timeout=$OPTARG ;;
*) printUsage; exit 1 ;;
esac
done
shift $((OPTIND - 1))
# $# should be at least 1 (the command to execute), however it may be strictly
# greater than 1 if the command itself has options.
if (($# == 0 || interval <= 0)); then
printUsage
exit 1
fi
exec "$@" &
pid=$!
((t = timeout))
while ((t > 0)); do
sleep $interval
# kill -0 exit code indicates if a signal may be sent to $pid process.
kill -0 $pid 2>/dev/null || exit 0
((t -= interval))
done
kill -s SIGKILL $pid
wait $pid 2>/dev/null