【原】用shell指令碼監視進程,崩潰掛掉後自動重啟

來源:互聯網
上載者:User

=================================================
本文為khler原作,轉載必須確保本文完整並完整保留原作者資訊及本文原始連結

Author: HeYuanHui
E-mail: khler@163.com
QQ:     23381103
MSN:   pragmac@hotmail.com
=================================================

 

如何保證服務一直運行?如何保證即使服務掛掉了也能自動重啟?在寫服務程式時經常會碰到這樣的問題。在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

 

 

 

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

 

    kill -9 $pidof $PWD/loader

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.