异想家博采众长的客厅

Linux程序守护脚本

2019.01.28

不废话,直接上脚本,【】注释的下发语句需要按需替换:

#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# 【待替换的进程名】
PRO_NAME=caddy

echo "异想家守护程序,当前路径:"
cur_dir=$(pwd)
echo $cur_dir

NUM=0
while( true )
do
NUM=`ps aux | grep -w ${PRO_NAME} | grep -v grep |wc -l`
#echo "${PRO_NAME}进程个数:${NUM},进程详情:"
#MSG=`ps aux | grep -w ${PRO_NAME}`
#echo ${MSG}
if [ "${NUM}" -lt "1" ];then
curDate=$(date "+%Y-%m-%d")
curTime=$(date "+%H:%M:%S")
echo "${PRO_NAME}异常退出,时间:${curDate} ${curTime}"
echo "${PRO_NAME}进程个数少于1,重启进程..."
# 【待替换的指令】
nohup ./caddy >./log_caddy_console.log &
fi
# 【待替换的时间,秒】
sleep 60
done

curDate=$(date "+%Y-%m-%d")
curTime=$(date "+%H:%M:%S")
echo "守护程序异常退出,时间:${curDate} ${curTime}"