shell 監控一個程序或者命令執行時間

這個需求是我一個“朋友”問我的,她想監控系統上一個命令,如果執行超過5分鐘還沒有結束,就要kill掉或者發郵件,短信之類的!

我最開始的思路比較簡單:

#!/bin/bash
#author junun
#blog http://angus717.blog.51cto.com
function angus() {
timestart_array=(`ps aux | grep test.sh | grep -v "grep" | awk '{print $2"_"$9}'`)
timenow=`date -d "3 minute ago" | awk '{print $4}'  | cut -d":" -f1-2`
declare -a arror_time=($@)
for i in `echo ${arror_time[*]}`;do
m=`echo $i | cut -d"_" -f1`
echo $m
n=`echo $i | cut -d"_" -f2`
echo $n
if [[ $n == $timenow ]];then
echo "$m will be killed"
kill $m
#mail -s "The process id ($m)is running time too long!" [email protected]
else
echo "this ok"
fi
done
}
angus

就是根據ps start那項判斷該命令執行多久了(爲了測試我寫了個死循環test.sh),但是人家說了這個不行,他們老大說判斷pid什麼的,然後他老大寫出來一個讓他很自豪的腳本,然後很很鄙視了小生一把!好吧,水平不高咱就虛心請教唄!人家還怕咱學會了,然後不鳥咱了,人活一口氣!

第二天果斷修改腳本:

[root@localhost ~]# cat nimawohenshengqi.sh
#!/bin/bash
#author junun
#blog http://angus717.blog.51cto.com
#
function checkdate() {

x=$1
y=$2
z=$3
nowtime=`/bin/date | awk '{print $2" "$3" "$4}'`
nowtime_day=`echo $nowtime | awk '{print $2}'`
nowtime_hour=`echo $nowtime | awk -F"[ |:]" '{print $3}'`
nowtime_minute=`echo $nowtime | awk -F"[ |:]" '{print $4}'`
if [ $x = $nowtime_day ];then
now_mins=`expr $nowtime_hour \* 60 + $nowtime_minute`
star_mins=`expr $y \* 60 + $z`
time_interval=`expr $now_mins - $star_mins`
else
echo "The process is running time too long!"
fi
}
function angus() {
runtime_interval=$1
[ -z "${runtime_interval:-}" ] && runtime_interval=5
timestart_array=(`ps aux | grep test.sh | grep -v "grep" | awk '{print $2}'`)
for i in `echo ${timestart_array[*]}`;do
m=`ls -ld  /proc/$i |  awk           '{print $7}'`
n=`ls -ld  /proc/$i |  awk -F"[ |:]" '{print $9}'`
a=`ls -ld  /proc/$i |  awk -F"[ |:]" '{print $10}'`
checkdate $m $n $a
if [[ $time_interval -ge $runtime_interval ]];then
echo "$i will be killed"
/bin/kill $i
else
echo "Command is ok"
fi
done
}
angus $1

修改過後可以接受參數定義(定義執行幾分鐘沒有的程序或者命令會被kill)總的來說是可以實現功能了,但是我感覺有點複雜,請夥伴們,給出更優秀的方案!

 

本來都頂格的,但是代碼貼上來都變了!!!!!!!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章