gpt4 book ai didi

php - 如何使用 pcntl_waitpid() 返回的 $status?

转载 作者:行者123 更新时间:2023-12-05 02:25:06 24 4
gpt4 key购买 nike

我正在进行 parent / worker 安排。 parent 将 worker PID 保存在一个数组中,通过以下循环不断检查它们是否仍然存在:

// $workers is an array of PIDs
foreach ($workers as $workerID => $pid) {
// Check if this worker still exists as a process
pcntl_waitpid($pid, $status, WNOHANG|WUNTRACED);

// If the worker exited normally, stop tracking it
if (pcntl_wifexited($status)) {
$logger->info("Worker $workerID exited normally");
array_splice($workers, $workerID, 1);
}

// If it has a session ID, then it's still living
if (posix_getsid($pid))⋅
$living[] = $pid;
}

// $dead is the difference between workers we've started
// and those that are still running
$dead = array_diff($workers, $living);

问题是 pcntl_waitpid() 总是将 $status 设置为 0,所以这个循环第一次运行时,父级认为它的所有子级已正常退出,即使它们仍在运行。我是否错误地使用了 pcntl_waitpid(),或者期望它做一些它没有做的事情?

最佳答案

很简单, child 没有退出或停止。您添加了 WNOHANG标志,所以它总是立即返回(它告诉函数不要等待事件)。你应该做的是检查 pcntl_waitpid 的返回值,看看是否返回了任何有值(value)的东西(假设你只想在状态发生变化时运行循环的内容):

foreach ($workers as $workerID => $pid) {
// Check if this worker still exists as a process
if (pcntl_waitpid($pid, $status, WNOHANG|WUNTRACED)) {
// If the worker exited normally, stop tracking it
if (pcntl_wifexited($status)) {
$logger->info("Worker $workerID exited normally");
array_splice($workers, $workerID, 1);
}
// If it has a session ID, then it's still living
if (posix_getsid($pid))⋅
$living[] = $pid;
}
}

关于php - 如何使用 pcntl_waitpid() 返回的 $status?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4586148/

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