我有一个 php-cli
脚本,由 cron
每 5 分钟
运行一次。因为这个时间间隔很短,多个进程
同时运行。这不是我想要的,因为此脚本必须在文本文件中写入一个每次递增的数字 id
。碰巧 writers
同时在这个文本文件上写,写的值是不正确的。
我曾尝试使用 php 的 flock
函数来阻止在文件中写入,当另一个进程正在写入文件但它不起作用时。
$fw = fopen($path, 'r+');
if (flock($fw, LOCK_EX)) {
ftruncate($fw, 0);
fwrite($fw, $latestid);
fflush($fw);
flock($fw, LOCK_UN);
}
fclose($fw);
所以我想解决这个问题的方法是创建一个 bash
脚本来验证是否有这个 php 脚本
的实例正在运行,如果是的话它应该等待直到它完成。但我不知道该怎么做,有什么想法吗?
最佳答案
我使用 bash 脚本
的解决方案是这样的:
exec 9>/path/to/lock/file
if ! flock -n 9 ; then
echo "another instance is running";
exit 1
fi
# this now runs under the lock until 9 is closed (it will be closed automatically when the script ends)
文件描述符 9>
在 /var/lock/file
中创建,并且 flock
将退出正在尝试运行的新进程,除非没有正在运行的脚本的其他实例。
How can I ensure that only one instance of a script is running at a time (mutual exclusion)?
关于php - 在最后一个完成之前不要运行 cron php 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23970981/