用linux那么久,到现在算是能写出来一点实用的脚本。记录一下。
这个脚本用来监视TARGET指明的程序,如果程序没有运行,则运行相应的启动脚本run.sh。并且,如果进程的cpu使用率达不到预期,可以杀死进程重新启动程序。功能比较简单,稳定性还在测试当中,run.sh里面可以简单的写一句”./TARGET“,TARGET即要运行的程序的名称,需与本脚本中的TARGET一样。写的依然不够理想,欢迎前辈指正。
#!/bin/bash
PROCESSID=0
THERMALDIR="/sys/devices/virtual/thermal/thermal_zone"
DEVICE="temp"
TARGET="executable"
RUNFILE="run.sh"
ISEXIST=0
CPUUSAGE=0
TARGETCPUUSAGE=100
cpuUsage()
{
if [[ $PROCESSID -gt 999 ]]; then
usage=`top -b -n 1 -d 1 | grep $TARGET | awk '{print $9}'`
echo "large"
else
usage=`top -b -n 1 -d 1 | grep $TARGET | awk '{print $9}'`
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
}
getPid()
{
PROCESSID=`pidof $TARGET` #`ps -eo pid,comm | grep $TARGET | awk '{print $1}'`
echo "pid:$PROCESSID" >> /tmp/program.log
}
runCalmcar()
{
if [ -e $TARGET -a -e $RUNFILE ]; then
./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
}
getThermal()
{
TEMP=(0 0 0 0 0 0 0)
for i in {0..7}; do
TEMP[$i]=`cat $THERMALDIR$i/$DEVICE`
done
echo "$(date) BCPU:${TEMP[0]} MCPU:${TEMP[1]} GPU:${TEMP[2]} AO:${TEMP[3]} TBoard:${TEMP[4]} TDiode:${TEMP[5]} Fan:${TEMP[6]}" >> /tmp/temperature.log
}
while true; do
echo "system start at $(date)" >> /tmp/program.log
count=0
while true; do
checkExist
getThermal
if [[ $ISEXIST -eq 1 ]]; then
getPid
cpuUsage
echo "cpuUsage:$CPUUSAGE" >> /tmp/program.log
if [[ $CPUUSAGE -lt $TARGETCPUUSAGE ]]; then
(( count++ ))
echo "count:$count" >> /tmp/program.log
if [[ $count -gt 9 ]];then
kill $PROCESSID
count=0
echo "$TARGET was killed at $(date) with pid $PROCESSID" >> /tmp/program.log
sleep 5
fi
else
count=0
echo "process ID:$PROCESSID" >> /tmp/program.log
fi
elif [[ $ISEXIST -eq 0 ]] ;then
count=0
runCalmcar
else
echo ""
fi
sleep 2
done
done