爱程序网

linux下的守护进程

来源: 阅读:

Linux下的常驻进程的作用不可忽略,但这里面的问题也不能忽略,怎么启动进程,怎么结束进程,怎么在进程挂掉之后重启进程都要设计的合理。下面看一个shell控制的php常驻进程的例子。

不废话,直接捞干货,上代码,通过代码来讲解更容易理解:

#!/bin/sh
#filename test.sh#绝对定位该文件的位置,不随执行目录而变化cd $(cd "$(dirname "$0")";pwd)readonly path=$(pwd)/file=$1;RunFile="${path}data/${file}.run"DieFile="${path}data/${file}.die"readonly file="${path}${file}.php"if [ ! -f "$file" ]; then    echo "please select a exists file"elif [ ! -f "$RunFile" ]; then
#这里进行判断如果RunFile文件不存在,则表示该进程不存在,下面启动进程
    echo $$>${RunFile}    while true        do            if [ ! -f $DieFile ]; then
            #这里如果DieFile文件不存在,则表示程序继续执行,否则进入else,执行退出操作                /usr/bin/php -f ${file}                touch $RunFile                sleep 1            else
            #如果DieFile文件存在清除RunFile和DieFile退出                if rm -rf $RunFile && rm -rf $DieFile ; then                    exit                fi            fi        doneelse#这里是在存在RunFile的情况下试图启动该进程
    oldpid=`cat $RunFile`    newpid=`ps aux | grep "process.sh $1" | grep -v grep | grep "$oldpid" | awk '{print $2}'`    if [[ $oldpid -eq $newpid ]]; then
    #如果RunFile中的进程号和正在运行的目标进程号一致,表明一切安好^_^        echo "the process is runing now"        exit    else
    #如果用RunFile中的进程号匹配不到正在运行的目标进程,则表示进程有问题,直接删除RunFile并结束运行的进程        echo "error situation,kill the run process and delete the run file"        ps aux | grep "process.sh $1" | grep -v 'grep' | awk '{print $2}' | grep -v $$ | xargs --no-run-if-empty kill        if [ $? -eq 0 ]; then            rm -f $RunFile        else            echo $?>${path}/data/error        fi    fifi

相关文章列表: