Linux监控脚本监控后台进程,当进程死掉后重新启动服务

本次代码主要检测nvr_service、apche2进程,如有另外的需要可以一次添加,步骤如下:

一、创建函数
function CheckProcess()
{
# Check whether the parameter is present
        if [ "$1" = "" ];then
            return 1
        fi

# $PROCESS_NUM is the number of $1
        PROCESS_NUM=`ps -ef | grep "$1" | grep -v "grep" | wc -l`
        if [ $PROCESS_NUM != 0 ];then
            return 1
        else
            return 0
        fi
}

#

    该函数用来检测进程的数量,当进程名字不存在,或者进程数为0时候返回0

二、循环,循环周期由sleep定义

while [ 1 ] ; do
        CheckProcess "nvr_service"
        if [ $? == 0 ];then
    # restart nvr_service
    /usr/local/sbin/nvr_service
    fi

    CheckProcess "apache2"
    if [ $? == 0 ];then
    # restart apache2
        service apache2 start
    fi

        CheckProcess "pubnub_get_message"
        if [ $? == 0 ];then
        # restart nvr_service
        /usr/local/sbin/pubnub_get_message &
        fi

        CheckProcess "pubnub_get_message"
        if [ $? == 0 ];then
        # restart nvr_service
        /usr/local/sbin/pubnub_get_message &
        fi


# Cycle every 5 seconds
sleep 5
done
根据第一步定义的函数返回值判断进程是否存在,当进程不存在时用相关的指令重启,如何代码中:“service apache2 restart”,
由于本次脚本是在root用户下运行,因此请注意调整

你可能感兴趣的:(Linux)