我有一个父母/工人的安排。父母将工人的pids保持在一个数组中,不断检查他们是否还活着以下循环:

// $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() 错误或期望它做不做的事情?

有帮助吗?

解决方案

简单,孩子尚未退出或停止。您添加了 WNOHANG 标志,因此它将始终立即返回(它告诉功能不要等待事件)。您应该做的是检查返回值 pcntl_waitpid 要查看是否返回任何有价值的东西(假设您只想在状态更改时运行循环的内容):

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;
    }
}    

其他提示

您确实是在使用 pcntl_waitpid() 错误”(请注意引号)

因为您正在使用 WNOHANG, 只要 如果 pcntl_waitpid() 返回孩子的pid,您可以评估什么 $status.

返回值 为了 pcntl_waitpid().

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top