如何保證服務一直運行?如何保證即使服務掛掉了也能自動重啟?在寫服務程序時經常會碰到這樣的問題。在Linux系統中,強大的shell就可以很靈活的處理這樣的事務。 下面的shell通過一個while-do循環,用ps -ef|grep 檢查loader進程是否正在運行,如果沒有運行,則啟動,這樣就保證了崩潰掛掉的進程重新被及時啟動。 必須注意兩點: 1、ps |grep 一個進程時必須加上其路勁,否則容易grep到錯誤的結果; 2、必須用 -v 從結果中去除grep命令自身,否則結果非空。 代碼如下: #!/bin/sh #===================== #YuanHui.HE #khler@163.com #===================== 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