khigia (owner)

Revisions

gist: 101192 Download_button fork
public
Description:
timeout on command run from bash
Public Clone URL: git://gist.github.com/101192.git
shell timeout
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
#!/bin/bash
 
if [ "$#" -lt 2 ]
then
cat<<EOF
Usage: $0 N <cmd>
Run <cmd> with a timeout of N seconds.
return result of <cmd>.
(<cmd> run in background process and is killed on timeout).
EOF
  exit -1
fi
 
# parse input
TO=$1
shift
CMD=$*
echo "$0: command=<$CMD> timeout=$TO"
 
# run the real command in background
$CMD &
CMDPID=$!
echo "$0: command PID=$CMDPID"
 
# run a process that wait TO and try to kill CMD process if it exists
(
  sleep $TO &&
  if [ -n "`ps -p ${CMDPID} | grep ${CMDPID}`" ] ;
  then
echo "$0: Timeout! kill command."
    kill $CMDPID
  fi
) &
MONPID=$!
echo "$0: monitor PID=$MONPID"
 
# wait end of CMD process (normal end or killed by MON)
trap "kill $CMDPID $MONPID; exit -1" INT KILL
wait $CMDPID
R=$?
echo "$0: command exited: $R"
 
# we kill the MON process (if still running after CMD finished)
if [ -n "`ps -p ${MONPID} | grep ${MONPID}`" ]
then
echo "$0: stopping monitor process"
  kill $MONPID
fi
 
# return result of CMD process
exit $R