以下是一個簡單的 Shell 腳本,用於監控指定程序是否運行,若未運行則自動啟動對應的 PHP 腳本。適用於 Beanstalkd 等長期運行的服務監控。
#!/bin/sh
# 取得 IP
IP=`/sbin/ifconfig eth1 | grep 'inet addr' | awk '{ print substr($2, index($2, ":")+1)}'`
# 監控函數
monitor() {
procname=$1
scriptname=$2
# 透過程序名稱查找進程
rc=$(ps -ef | grep $procname | grep -v grep | wc -l)
if [ $rc -eq 0 ]; then
echo "$procname start"
php $scriptname &
else
echo "$procname running"
fi
sleep 1
}
# 監控 beanstalkd_service
monitor "beanstalkd_service" "/home/www/phpxiu/public/beanstalkd_service.php"
monitor.sh 並賦予執行權限(chmod +x monitor.sh)。crontab 定期執行(如每分鐘):* * * * * /path/to/monitor.sh。procname 為進程關鍵字,scriptname 為對應的 PHP 啟動腳本路徑。