我有一个php脚本,分叉和父调用pnctl_wait()。根据php手册,pcntl_wait()应暂停执行当前进程,直到子进程退出。但这不会发生。 父进程根本不会等待,并立即执行下一行。
我试图在下面的小样本脚本中复制该问题
<?php
$parentpid=getmypid();
declare(ticks=1);
$apid = pcntl_fork();
if ($apid == -1) {
die('could not fork for client '.$client);
} else if ($apid) { //parent
pcntl_wait($status,WNOHANG); //Protect against Zombie children
/* Parent does not wait here */
print "PARENT $parentpid has forked $apid \n";
sleep(100);
} else { // child
$pid = getmypid();
print "CHILD $pid is sleeping\n";
sleep(40);
}
?>
答案 0 :(得分:3)
您不希望在此处选择WNOHANG
。只需使用:
pcntl_wait($status);
如果您通过WNOHANG
pcntl_wait()
,则不会等待孩子返回。它仅报告已被终止的孩子。
整个示例应如下所示:
$parentpid = getmypid();
$apid = pcntl_fork();
if ($apid == -1) {
die('could not fork for client '.$client);
} else if ($apid) {
// Parent process
print "PARENT $parentpid has forked $apid \n";
// Wait for children to return. Otherwise they
// would turn into "Zombie" processes
pcntl_wait($status);
} else {
// Child process
$pid = getmypid();
print "CHILD $pid is sleeping\n";
sleep(40);
}