红联Linux门户
Linux帮助

linux shell进程监视脚本

发布时间:2017-06-26 09:39:12来源:linux网站作者:嵌入梦想
用linux那么久,到现在算是能写出来一点实用的脚本。记录一下。
 
这个脚本用来监视TARGET指明的程序,如果程序没有运行,则运行相应的启动脚本run.sh。并且,如果进程的cpu使用率达不到预期,可以杀死进程重新启动程序。功能比较简单,稳定性还在测试当中,run.sh里面可以简单的写一句”./TARGET“,TARGET即要运行的程序的名称,需与本脚本中的TARGET一样。写的依然不够理想,欢迎前辈指正。
 
#!/bin/bash
PROCESSID=0
TARGET="test"
RUNFILE="run.sh"
ISEXIST=0
CPUUSAGE=0
TARGETCPUUSAGE=100
cpuUsage()
{
if [[ $PROCESSID -gt 9999 ]]; then
usage=`top -n 1 -d 1 | grep $TARGET | awk '{print $9}'`
echo "large"
else
usage=`top -n 1 -d 1 | grep $TARGET | awk '{print $10}'`
echo "small"
fi
CPUUSAGE=`echo $usage | awk -F. '{print $1}'`
}
checkExist()
{
server=$(ps -aux | grep $TARGET | grep -v grep | wc -l)
if [[ $server -eq 0 ]]; then
echo "thread doesn't exist'" >> /tmp/program.log
ISEXIST=0
elif [[ $server -eq 1 ]]; then
echo "thread exist" >> /tmp/program.log
ISEXIST=1
else
ISEXIST=2
echo "there are more than two process running" >> /tmp/program.log
fi
}
checkExist
getPid()
{
PROCESSID=`ps -eo pid,comm | grep $TARGET | awk '{print $1}'`
echo "pid:$PROCESSID" >> /tmp/program.log
}
runCalmcar()
{
if [ -e $TARGET -a -e $RUNFILE ]; then
nohup ./run.sh 2>&1 >> /tmp/program.log &
echo "execute run.sh" >> /tmp/program.log
else
echo "there is no executable file exist" >> /tmp/program.log
fi
}
while true; do
echo "system start at $(date)" >> /tmp/program.log
while true; do
checkExist
if [[ $ISEXIST -eq 1 ]]; then
getPid
cpuUsage
echo "cpuUsage:$CPUUSAGE" >> /tmp/program.log
count=0
if [[ $CPUUSAGE -lt $TARGETCPUUSAGE ]]; then
((count++))
echo "count:$count" >> /tmp/program.log
if [[ $count -gt 9 ]];then
`kill $PROCESSID`
echo "$TARGET was killed at $(date) with pid $PROCESSID" >> /tmp/program.log
fi
runCalmcar
fi
echo "process ID:$PROCESSID" >> /tmp/program.log
else
runCalmcar
fi
sleep 2
done
done
 
本文永久更新地址:http://www.linuxdiyf.com/linux/31723.html