守护进程--shell脚本


用shell写一个简单的守护进程脚本, 
以下脚本守护goahead进程,goahead进程起来后会有多个线程 

启动此脚本后,进入循环,通过ps命令查看goahead进程数量,判断重启或杀死异常进程

#! /bin/sh  
#进程名字 
PRO_NAME=goahead  

echo "=============keep.sh  pid : $$ ================"

while true ; do  
    #用ps获取$PRO_NAME进程数量  
    NUM=`ps aux | grep ${PRO_NAME} | grep -v grep |wc -l`  
    #echo $NUM  
    #少于1,重启进程  
    if [ "${NUM}" -lt "1" ];then  
        echo "${PRO_NAME} was killed"  
        echo "restart ${PRO_NAME} now"
        ${PRO_NAME} &  
    #大于3,杀掉所有进程,重启  
    elif [ "${NUM}" -gt "3" ];then  
        echo "more than 3 ${PRO_NAME},killall ${PRO_NAME}"  
        killall $PRO_NAME  
        echo "restart ${PRO_NAME} now"
        ${PRO_NAME} &  
    fi  

    #kill僵尸进程  
    NUM_STAT=`ps aux | grep ${PRO_NAME} | grep T | grep -v grep | wc -l`  
    if [ "${NUM_STAT}" -gt "0" ];then  
        killall ${PRO_NAME}  
        ${PRO_NAME} &  
    fi  
    sleep 5
done  

exit 0 
参考文章 csdn博客:  http://blog.csdn.net/guoyilongedu/article/details/42835931

你可能感兴趣的:(linux)