函数名称:pcntl_waitpid()
适用版本:PHP 4 >= 4.1.0, PHP 5, PHP 7
函数描述:等待或返回fork的子进程状态
用法: pcntl_waitpid(int $pid, int &$status [, int $options = 0 [, array &$rusage ]]) : int|bool
参数:
返回值:
示例:
$pid = pcntl_fork();
if ($pid == -1) {
die('fork 失败');
} elseif ($pid == 0) {
// 子进程代码
exit(0);
} else {
// 父进程代码
$status = 0;
$result = pcntl_waitpid($pid, $status);
if ($result == -1) {
echo "等待子进程失败\n";
} else {
if (pcntl_wifexited($status)) {
echo "子进程正常终止,退出状态为:" . pcntl_wexitstatus($status) . "\n";
} elseif (pcntl_wifsignaled($status)) {
echo "子进程被信号终止,终止信号为:" . pcntl_wtermsig($status) . "\n";
} elseif (pcntl_wifstopped($status)) {
echo "子进程进入暂停状态,暂停信号为:" . pcntl_wstopsig($status) . "\n";
}
}
}
以上示例中,首先使用pcntl_fork()创建了一个子进程。子进程在这里被简化为直接退出。父进程调用pcntl_waitpid()等待子进程的终止,并获取子进程的退出状态。然后根据不同的退出状态使用pcntl_wifexited()、pcntl_wifsignaled()和pcntl_wifstopped()进行判断,并使用相应的pcntl_wexitstatus()、pcntl_wtermsig()和pcntl_wstopsig()函数获取更详细的信息。