寫守護行程不一定要用 Shell。用 PHP 一樣能做到啟動、停止與自動重啟,語法親手可讀,維護起來更直覺。本文以一個完整的 start() 函式說明整個機制,並搭配 crontab 定時巡檢,確保程序掛掉後能被拉回來。
核心只有三件事:用一個 .run 檔記錄目前行程的 PID 與最後活動時間;用一個 .die 檔當作停止旗標;再用 crontab 每隔幾分鐘執行一次腳本,檢查 PID 是否還對得上、活動時間是否中斷過久,若異常就砍掉重啟。
<?php
function start($file){
$path = dirname(__FILE__).'/';
$runfile = $path.$file.'.run';
$diefile = $path.$file.'.die';
$file = $path."data/{$file}.php";
clearstatcache();
if(file_exists($runfile)){
$oldpid = file_get_contents($runfile);
$nowpid = shell_exec("ps aux | grep 'php -f process.php' | grep ${oldpid} | awk '{print $2}'");
// runfile 中的 pid 仍能匹配到執行中的行程,且距上次活動未滿 5 分鐘,則視為正常
if(($oldpid == $nowpid) && (time() - fileatime($runfile) < 300)){
echo "$file is circle runing no";
return;
}else{
// pid 不符,或超過 300 秒未更新活動時間,直接結束並重啟
$pid = file_get_contents($runfile);
shell_exec("ps aux | grep 'php -f process.php' | grep {$pid} | xargs --if-no-run-empty kill");
}
}else{
// 寫入目前行程 pid
if(!($newpid = getmypid()) || !file_put_contents($runfile,$newpid)){
return;
}
while(true){
// 偵測到結束旗標,清掉相關檔案後退出
if(file_exists($diefile) && unlink($runfile) && unlink($diefile)){
return;
}
/* 這裡放守護行程實際要做的業務 */
file_put_contents($file,"I'm Runing Now".PHP_EOL,FILE_APPEND);
/***********************/
touch($runfile); // 更新活動時間
sleep(5);
}
}
}
start("test");
1. 別忘了 clearstatcache()。PHP 會快取檔案狀態資訊,同一支腳本裡若多次檢查同一個檔案,不快取就會拿到過期結果。受影響的函式包含 stat()、lstat()、file_exists()、is_writable()、is_readable()、is_executable()、is_file()、is_dir()、is_link()、filectime()、fileatime()、filemtime()、fileinode()、filegroup()、fileowner()、filesize()、filetype()、fileperms()。
2. 重啟條件有兩種。每次重複執行腳本時都會先檢查:PID 對不上,或距離上次循環已超過 300 秒,兩者任一成立就重啟。因此記得在每次循環結尾呼叫 touch() 更新時間戳,否則會被誤判為卡死。
3. 自動重啟靠 crontab。把腳本掛進排程:
crontab -e # 進入編輯模式(inset 模式)後加入: */3 * * * * /usr/bin/php -f process.php # 每 3 分鐘執行一次,避免行程意外終止後無人處理
做到這一步,基本的守護機制就完整了。若要對應具體業務,只要把 while 迴圈中那段佔位邏輯替換成自己的處理流程即可。