linux shell程序監視指令碼
阿新 • • 發佈:2018-12-23
用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