我有一个php脚本每分钟从cron运行一次。但有时它的运行时间超过1分钟。
我的问题是:保证现在只有一个进程正在运行的最佳方法是什么?
我使用了这段代码:
$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)
}
如果有一个"some_script"进程从cron中运行,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
如果输出中有两行以上,我就会调用exit()函数。
我想问:我这样做对吗?还是有更好的方法?
非常感谢您的帮助。