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

本文讨论了如何使用PHP的pcntl_waitpid函数避免僵尸进程,并给出了一个示例,同时提到了编译选项--enable-sigchild对pcntl_waitpid的影响。阅读者将了解如何正确处理子进程并确保资源释放。
摘要由CSDN通过智能技术生成

用户评论:

brian dot ngure at gmail dot com (2009-07-08 08:03:22)

Please note that you must use bitwise OR | in the following:

"The value of options is the value of zero or more of the following two global constants OR'ed together"

i.e.

WNOHANG | WUNTRACED

tunderzone at gmail dot com (2009-06-25 06:26:18)

A better way to do this and not end up having zombie processes until all child processes ends is like this:

$i=0;$starttime=microtime(TRUE);$pid_arr= array();

while ($i

{$pid=pcntl_fork();

if ($pid== -1)

{

die('could not fork');

}

else

{

if ($pid)// parent{$pid_arr[$i] =$pid;

}

else// child{performSomeFunction($i+1);

}

}$i++;

}

while(count($pid_arr) >0)

{$myId=pcntl_waitpid(-1,$status,WNOHANG);

foreach($pid_arras$key=>$pid)

{

if($myId==$pid) unset($pid_arr[$key]);

}usleep(100);

}$elapsed=microtime(TRUE) -$starttime;

print"\n==> total elapsed: ".sprintf("%f secs.\n",$elapsed);?>

saguto dot l7cc at gmail dot com (2008-04-09 21:09:05)

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.

Kevin (2006-05-10 15:40:24)

---

while ($i < intval($argv[1]))

{

$pid = pcntl_fork();

if ($pid == -1)

{

die('could not fork');

}

else

{

if ($pid) // parent

{

$pid_arr[$i] = $pid;

}

else // child

{

performSomeFunction($i+1);

}

}

$i++;

}

---

careful, this will create a lot more children than you probably expect. You must return or exit after performSomeFunction($i+1); ie,

else // child

{

performSomeFunction($i+1);

exit(0);

}

admin at albert dot us dot com (2006-03-06 10:48:55)

Here's a decent example of the pcntl_waitpid() call:

$i = 0;

$starttime = microtime(TRUE);

$pid_arr = array();

while ($i < intval($argv[1]))

{

$pid = pcntl_fork();

if ($pid == -1)

{

die('could not fork');

}

else

{

if ($pid) // parent

{

$pid_arr[$i] = $pid;

}

else // child

{

performSomeFunction($i+1);

}

}

$i++;

}

foreach ($pid_arr as $pid)

{

// we are the parent

pcntl_waitpid($pid, $status);

}

$elapsed = microtime(TRUE) - $starttime;

print "\n==> total elapsed: " . sprintf("%f secs.\n", $elapsed);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值