You have a command and want to kill it after a certain time if it hasn’t finished.
This script does it for you:
timeoutwrapper.sh
#!/bin/bash
# License: BSD License
# author: Ram
# author: Johannes Buchner
TIMEOUT=$1
shift
COMMAND="$*"
if [[ "$TIMEOUT" == "" ]] || [[ "$COMMAND" == "" ]]; then
echo "USAGE: $0 <seconds to wait> <command with arguments>"
exit
fi
$COMMAND &
PRODPID=$!
export PRODPID
# record own PID
export PID=$$
# define exit function
exit_timeout() {
echo "Timeout. Checking for unfinished."
for i in ${PRODPID} ; do
ps -p $i |grep -v "PID TTY"
if [ $? == 0 ] ; then
# process still alive
echo "Sending SIGTERM to process $i"
kill $i
fi
done
# timeout exit
exit
}
# Handler for signal USR1 for the timer
trap exit_timeout SIGUSR1
# starting timer in subshell. It sends a SIGUSR1 to the father if it timeouts.
export TIMEOUT
(sleep $TIMEOUT ; kill -SIGUSR1 $PID) &
# record PID of timer
TPID=$!
# wait for all production processes to finish
wait ${PRODPID}
# Normal exit
echo "All processes ended normal"
# kill timer
kill $TPID
Usage examples:
$ bash timeoutwrapper.sh
USAGE: timeoutwrapper.sh <seconds to wait> <command with arguments>
$ bash timeoutwrapper.sh 1 sleep 3
Timeout. Checking for unfinished.
26612 pts/3 00:00:00 sleep
Sending SIGTERM to process 26612
$ bash timeoutwrapper.sh 4 sleep 3
All processes ended normal
$ bash timeoutwrapper.sh 2 du -sh .
Timeout. Checking for unfinished.
26622 pts/3 00:00:00 du
Sending SIGTERM to process 26622
$
PS: I found the script here and adopted it
http://redflo.de/tiki-index.php?page=Bash+script+with+timeout+function
Recent Comments