gpt4 book ai didi

php - 如何在php中找到PID

转载 作者:可可西里 更新时间:2023-11-01 00:35:10 24 4
gpt4 key购买 nike

我正在编写一个将通过 cron 运行的 php 脚本。它的任务是调用其他的php脚本。调用的脚本也可以在外部执行。我想要的是当一个文件正在执行时,它不应该同时执行。为清楚起见,请考虑以下内容

假设有一个脚本 master.php 依次调用另外两个脚本 script1.php 和 script2.php。现在,一旦调用 script1.php,它就会开始执行并需要 10 分钟才能完成处理。这 Script1.php 也可以在这 10 分钟内由用户单独运行。

我想做的是,当这个脚本在处理过程中时,它不应该只并行执行。

有办法实现吗? (也许通过检查 script1.php 的 PID)。

提前致谢。

最佳答案

这就是我使用 pid 文件的方式。此外,如果脚本运行时间超过 300 秒,它将被杀死:

$pid_file = '/var/run/script1.pid';
if (file_exists($pid_file)) {
$pid = file_get_contents($pid_file);
if ($pid && file_exists('/proc/' . $pid)) {
$time = filemtime($pid_file);
if (time() - $time > 300) {
posix_kill($pid, 9);
} else {
exit("Another instance of {$argv[0]} is running.\n");
}
}
}

$pid = posix_getpid();
if (!file_put_contents($pid_file, $pid)) exit("Can't write pid file $pid_file.\n");

然后在脚本末尾取消链接 pid 文件:

unlink($pid_file);

如果您想在第一个实例完成时运行脚本 - 将 exit() 替换为 sleep(1) 并将整个 block 放入一个循环中。

关于php - 如何在php中找到PID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10430462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com