一、成品经过长期的自动化测试后,发现偶然出现主进程异常退出的现象,于是受开发者的委托,用SHELL写一段监视程序,要求如下:
主进程退出后,自动重启这个主进程。
主进程程序状态为Z时,重启该主进程。
主进程的CPU负载超过95%时,3分钟内持续在高位运行时,重启应用程序。
直接上代码。
#!/bin/sh
##################################
#Author : 154353294@qq.com
#Date : 2015-10-1
#Funtion: Monitor MainProcess's status,
# IF the status of MainProcess process is Z ,then reboot system;
# IF the MainProcess process exit abnormally,then reboot application;
# IF the CPU usage of MainProcess process above 95% duration 3mins, then reboot applicaion.
# The log of shell output to current directory named HealthMonitor_YYYYMMDDHHMMSS.log.
##################################
var=$0
LOGFILE=${
var%%.sh}_`date "+%Y%m%d%H%M%S"`.log
echo "`date "+%Y-%m-%d %H:%M:%S"`"#"Start " > $LOGFILE
sec=3
t_start=0
t_perCurrent=0
t_current=0
total=0
MaxTimes=60 ##3*60=180s
#获取主进程的PID,内存使用率,CPU使用率,以及名称。
eval $(top -n 1| grep "MainProcess" | grep -v grep | awk {'printf("mainPID=%s;myStatus=%s;memInfo=%s;cpuRatio=%s;pName=%s\n",$1,$4,$5,$7,$8)'})
echo `date "+%Y-%m-%d %H:%M:%S"`"#"$mainPID $myStatus ${memInfo%%m} ${cpuRatio%%%} $pName >> $LOGFILE