PHP 8.3.4 Released!

pcntl_waitpid

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

pcntl_waitpid等待或返回 fork 的子进程状态

说明

pcntl_waitpid(
    int $process_id,
    int &$status,
    int $flags = 0,
    array &$resource_usage = []
): int

挂起当前进程的执行直到参数 process_id 指定的进程号的进程退出, 或接收到一个信号要求中断当前进程或调用一个信号处理函数。

如果 process_id 指定的子进程在此函数调用时已经退出(俗称僵尸进程),此函数 将立刻返回。关于 waitpid 更详细的规范请参见系统的 waitpid(2)手册。

参数

process_id

参数 process_id 的值可以是以下之一:

process_id 可选值
< -1 等待任意进程组 ID 等于参数 process_id 给定值的绝对值的进程。
-1 等待任意子进程;与 wait 函数行为一致。
0 等待任意与调用进程组 ID 相同的子进程。
> 0 等待进程号等于参数 process_id 值的子进程。

注意:

指定 -1 作为 process_id 的值等同于 pcntl_wait() 提供(负的 flags)。

status

pcntl_waitpid() 将会存储状态信息到 status 参数上,这个通过 status 参数返回的状态信息可以用以下函数 pcntl_wifexited()pcntl_wifstopped()pcntl_wifsignaled()pcntl_wexitstatus()pcntl_wtermsig() 以及 pcntl_wstopsig() 获取其具体的值。

flags

flags 的值可以是以下两个常量中 0 个或多个 OR 运算的结果:

flags 可用的值
WNOHANG 如果没有子进程退出立刻返回。
WUNTRACED 子进程已经退出并且其状态未报告时返回。

返回值

pcntl_waitpid() 返回退出的子进程进程号,发生错误时返回 -1,如果使用 WNOHANG 并且没有可用子进程时返回 0。

参见

add a note

User Contributed Notes 3 notes

up
3
saguto dot l7cc at gmail dot com
15 years ago
please note, if you using configure option --enable-sigchild(Enable PHP's own SIGCHLD handler) when complie php(under linux 2.6.18-53.1.13.el5.centos.plus and php 5.2.5 as I know), pcntl_waitpid and pcntl_wait in php script would never return the child pid, because the build in handle get it first.
up
0
fx4084 at gmail dot com
9 years ago
<?php
$childs
= array();

// Fork some process.
for($i = 0; $i < 10; $i++) {
$pid = pcntl_fork();
if(
$pid == -1)
die(
'Could not fork');

if (
$pid) {
echo
"parent \n";
$childs[] = $pid;
} else {
// Sleep $i+1 (s). The child process can get this parameters($i).
sleep($i+1);

// The child process needed to end the loop.
exit();
}
}

while(
count($childs) > 0) {
foreach(
$childs as $key => $pid) {
$res = pcntl_waitpid($pid, $status, WNOHANG);

// If the process has already exited
if($res == -1 || $res > 0)
unset(
$childs[$key]);
}

sleep(1);
}
?>
up
-1
renmengyang567 at gmail dot com
4 years ago
<?php

declare(ticks = 1);
function
zp_handler($signal) {
$id = pcntl_waitpid(-1, $status, WNOHANG);
if (
pcntl_wifexited($status))
{
printf("Removed Chlid id: %d \n",$id);
printf("Chlid status: %d \n",pcntl_wexitstatus($status));
}
}

//pcntl_signal_dispatch();
pcntl_signal(SIGCHLD, "zp_handler");
//pcntl_signal_dispatch();
//

$pid = pcntl_fork();
if (
$pid == 0)
{
print
"#1 Hi, I'm child process".PHP_EOL;
sleep(3);
return
10;
}
else
{
print
"#1parent process id:".$pid.PHP_EOL;
$pid = pcntl_fork();
if (
$pid == 0)
{ print
"#2 Hi, I'm child process".PHP_EOL;
sleep(10);
exit(
20);
}
else
{
print
"#2parent process id:".$pid.PHP_EOL;
for (
$i=0; $i <10 ; $i++) {
print
"wait..".PHP_EOL;
sleep(10);
}
}
}
?>
To Top