It is neccessary we can control how long the command take in some situation .
I expirience it these days and I understand the way to achieve the goal.
Below is the script sample:
#cat a.sh
#!/bin/bash
#
#author: langsuifeng210@163.com
#date: 2009-01-06
#
#-------------------------------------------------------------------------------------------
AlarmHandler()
{
echo "Cmd took too long"
KillSubProcs
#send alarm msg
#exit 14
}
KillSubProcs()
{
echo "kill: ${CHPROCIDS:-$!}"
kill -9 ${CHPROCIDS:-$!}
if [ $? -eq 0 ]
then
echo "Sub-processes killed."
fi
}
#
#Set execute time of ${pid} doesn't exceed ${DEF_TOUT} and kill -14 $$ for awake AlarmHandler
#
SetTimer()
{
DEF_TOUT=${1:-10};
if test $DEF_TOUT -ne 0
then
sleep $DEF_TOUT && echo "overtime: $ERRMSG" && kill -9 ${pid} && kill -s 14 $$ &
CHPROCIDS="$CHPROCIDS $!"
TIMERPROC=$!
#echo $TIMERPROC
fi
}
#
#if execute time of ${pid} didn't exceed ${DEF_TOUT}, SetTimer should be killed.
#
UnsetTimer()
{
sleep 1;EXIST=`ps auxw | grep $TIMERPROC | grep -v 'grep' | wc -l`
if [ ${EXIST} -gt 0 ];then
kill -9 $TIMERPROC
fi
}
#
#sample
#
trap AlarmHandler 14
sleep 5 &
CHPROCIDS="$CHPROCIDS $!"
pid=$!
echo $pid
SetTimer $1
wait $pid
UnsetTimer
echo "Here is End!"
#./a.sh 1
9902
overtime:
Cmd took too long
kill: 9902 9903
Sub-processes killed.
/tmp/a.sh: line 38: 9902 Killed sleep 5
/tmp/a.sh: line 38: 9903 Killed sleep $DEF_TOUT && echo "overtime: $ERRMSG" && kill -9 ${pid} && kill -s 14 $$
Here is End!
#./a.sh 7
9919
Here is End!
阅读(685) | 评论(0) | 转发(0) |