Shell脚本之监视主进程的运行状态,异常退出后自动重启

本文介绍了如何使用Shell脚本来监视主进程的运行状态,当主进程异常退出或者CPU负载过高时,脚本将自动重启该主进程,确保程序的稳定运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、成品经过长期的自动化测试后,发现偶然出现主进程异常退出的现象,于是受开发者的委托,用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值