代码改变世界

linux二重启动防止

2014-04-15 14:07  纯情蛋蛋汤  阅读(282)  评论(0编辑  收藏  举报
#!/bin/bash
# 2重起動チェック
function checkDuplicate()
{
    local RET=0
    local base=${0##*/}
    local pidfile="/tmp/${base}.pid"

    while true; do
        if ln -s $$ ${pidfile} 2> /dev/null
        then
            # 起動OK
            RET=0 && break
        else
            p=$(ls -l ${pidfile} | sed 's@.* @@g')
            if [ -z "${p//[0-9]/}" -a -d "/proc/$p" ]; then
                local mypid=""
                for mypid in $(pgrep -f ${base})
                do
                    [ ${p} -eq ${mypid} ] && RET=1 && break
                done;
            fi

            [ ${RET} -ne 0 ] && break
        fi

        rm -f ${pidfile}
    done

    # チェック結果を判定して、pidファイルを作成する。
    # 正常終了、シグナルを検知するとpidファイルを削除する。
    if [ ${RET} -eq 0 ]; then
        trap "rm -f ${pidfile}; exit 0" EXIT
        trap "rm -f ${pidfile}; exit 1" 1 2 3 15
    fi

    return ${RET}
}

用法

 2重起動チェック
checkDuplicate
if [ 0 -ne $? ]; then
        # ここにエラー処理を書く
fi

--------------------------------------------------------------------------------


转载自:http://qiita.com/KurokoSin/items/0eddf05818b89b627102