Chinaunix首页 | 论坛 | 博客
  • 博客访问: 150732
  • 博文数量: 52
  • 博客积分: 1410
  • 博客等级: 上尉
  • 技术积分: 490
  • 用 户 组: 普通用户
  • 注册时间: 2007-11-05 12:05
文章分类

全部博文(52)

文章存档

2013年(1)

2010年(3)

2009年(6)

2008年(25)

2007年(17)

我的朋友

分类:

2009-01-07 10:16:45

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) |
给主人留下些什么吧!~~