如何使用 pcntl_waitpid() 返回的 $status?
我正在进行家长/工人安排。父级将工作进程 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(),或者期望它做一些它没有做的事情?
I have a parent/worker arrangement going on. The parent keeps the worker PIDs in an array, constantly checking that they are still alive with the following loop:
// $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);
The problem is that pcntl_waitpid()
is always setting $status
to 0, so the very first time this loop is run, the parent thinks that all of its children have exited normally, even though they are still running. Am I using pcntl_waitpid()
incorrectly, or expecting it to do something that it doesn't?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很简单,孩子还没有退出或者停止。您添加了
WNOHANG
标志,所以它总是立即返回(它告诉函数不要等待事件)。您应该做的是检查 pcntl_waitpid 的返回值,看看是否返回了任何有价值的内容(假设您只想在状态发生更改时运行循环的内容):Simple, the child has not exited or stopped. You added the
WNOHANG
flag, so it will always return immediately (It tells the function not to wait for an event). What you should do is check the return value ofpcntl_waitpid
to see if anything of value was returned (assuming that you only want to run the contents of the loop if there's a status change):您确实“使用
pcntl_waitpid()
错误”(注意引号)由于您使用的是
WNOHANG
,仅如果pcntl_waitpid ()
返回子进程的 PID,您可以评估$status
中的内容。请参阅
pcntl_waitpid()
返回值 >。You're indeed "using
pcntl_waitpid()
wrong" (Note the quotes)Since you're using
WNOHANG
, only ifpcntl_waitpid()
returns the child's PID, you may evaluate what's in$status
.See return values for
pcntl_waitpid()
.