天天看點

linux下監視程序 崩潰挂掉後自動重新開機的shell腳本

 如何保證服務一直運作?如何保證即使服務挂掉了也能自動重新開機?在寫服務程式時經常會碰到這樣的問題。在Linux系統中,強大的shell就可以很靈活的處理這樣的事務。

    下面的shell通過一個while-do循環,用ps -ef|grep 檢查loader程序是否正在運作,如果沒有運作,則啟動,這樣就保證了崩潰挂掉的程序重新被及時啟動。

    必須注意兩點:

    1、ps |grep 一個程序時必須加上其路勁,否則容易grep到錯誤的結果;

    2、必須用 -v 從結果中去除grep指令自身,否則結果非空。

    複制代碼代碼如下:

    #!/bin/sh

    while :

    do

    echo "Current DIR is " $PWD

    stillRunning=$(ps -ef |grep "$PWD/loader" |grep -v "grep")

    if [ "$stillRunning" ] ; then

    echo "TWS service was already started by another way"

    echo "Kill it and then startup by this shell, other wise this shell will loop out this message annoyingly"

    kill -9 $pidof $PWD/loader

    else

    echo "TWS service was not started"

    echo "Starting service ..."

    $PWD/loader

    echo "TWS service was exited!"

    fi

    sleep 10

    done

    如果啟動此shell時發現程序已經存在,說明以别的方式啟動了程序而不是此shell,那麼它會持續提醒找到程序,解決辦法是,要麼隻用此shell啟動服務,要麼一經發現以其他方式啟動的服務即kill掉,上面的語句就是這麼幹的:

繼續閱讀