Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

用 Shell 守護常駐服務:偵測不到就自動拉起

有些 PHP 寫的常駐腳本跑久了會莫名消失,靠人盯著顯然不現實。與其反覆重啟,不如丟給 cron 每分鐘檢查一次,發現進程不在就重新拉起。

#!/bin/sh

先確認支付處理腳本還活著:

kill_result=`ps aux | grep 'index.php' | grep -v grep | wc -l`
if [ $kill_result -eq 0 ] ; then
  nohup /usr/local/php/bin/php /var/www/q5.youxigu.com/pay/index.php &
fi

再確認取號處理腳本:

kill_result=`ps aux | grep 'autosn_processing.php' | grep -v grep | wc -l`
if [ $kill_result -eq 0 ] ; then
  nohup /usr/local/php/bin/php /var/www/q5.youxigu.com/getsn/autosn_processing.php &
fi

幾個實作上的提醒:grep -v grep 是為了排除 grep 自身那一列,否則計數永遠至少為 1;nohup ... & 讓程序脫離終端在背景執行。若守護的服務數量變多,建議把「檢查」與「啟動命令」抽成陣列或改用 supervisor 這類工具管理,会比不断堆叠 if 區塊好維護。同時别忘了把腳本輸出導向日誌,否則出問題時完全無跡可尋。

Copyright © Linux教程網 All Rights Reserved