我有一個從cron運行每分鐘的php腳本。但有時它的工作時間超過1分鐘。 我的問題是:確保現在只有一個進程正在運行的最佳方式是什麼?確保在Linux上只有一個正在運行的PHP進程
我用這個代碼:
$output = shell_exec('ps aux | grep some_script.php | grep -v grep'); //get all processes containing "some_script.php" and exclude current grep process
$trimmed = rtrim($output, PHP_EOL); //trim newline symbol in the end
$processes = explode(PHP_EOL, $trimmed); //get the array of lines (i.e. processes)
$procCnt = count($processes); //get number of lines
if ($procCnt > 2) {
echo "busy\n";
exit(); //exit if number of processes more than 2 (see explaination below)
}
如果有cron中運行一個some_script過程,了shell_exec返回類似的東西:在輸出
apache 13593 0.0 0.0 9228 1068 ? Ss 18:20 0:00 /bin/bash -c php -f /srv/www/robot/some_script.php 2>&1
apache 13602 0.0 0.0 290640 10544 ? S 18:20 0:00 php -f /srv/www/robot/some_script.php
所以超過2,如果我有線條,我致電退出()
我想問:我是否正確?或者,還有更好的方法?
任何幫助,將不勝感激
我應該添加,就我所知__ PHP的mkdir是原子。如果我錯了,那麼使用關機功能的羊羣可能會更好。 – Izkata
我不知道register_shutdown_function。非常感謝你!它訣竅 – Curious
register_shutdown_function可能無法調用某些類型的錯誤。要真正實現它,我會爲鎖添加「過期」。檢查文件夾的filemtime,如果超過15分鐘,刪除它並繼續使用cron(你也可以用腳本殺死所有php進程)。 –