PHP多进程编程
时间:2007-12-11 来源:phpor
摘自PHP手册的代码:
?php
declare(ticks = 1);
$max=5;
$child=0;
// function for signal handler
function sig_handler($signo) {
global $child;
switch ($signo) {
case SIGCHLD:
echo "SIGCHLD received\n";
$child--;
}
}
// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");
while (1){
$child++;
$pid=pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
// we are the parent
if ( $child >= $max ){
pcntl_wait($status);
}
} else {
// we are the child
echo "\t Starting new child | now we de have $child child processes\n";
// presumably doing something interesting
sleep(rand(3,5));
exit;
}
}
?>
从中学到了什么:
1.子进程结束后会给父进程一个信号SIGCHLD;
2.子进程和父进程的共享代码段最好什么也不要写;
3.该程序一直运行时好像是保证了子进程的个数不超过max个,但是要退出时能确定还要等待几个子进程吗?经下面程序的测试答案是否定的。
请看下面的测试:
?php
/*
这个程序可以保证子进程不会多于max个,但是却无法保证要退出时还要等几个子进程
*/
declare(ticks = 1);
$max=5;
$child=0;
// function for signal handler
function sig_handler($signo) {
global $child;
switch ($signo) {
case SIGCHLD:
echo "SIGCHLD received\n";
$child--;
}
}
// install signal handler for dead kids
pcntl_signal(SIGCHLD, "sig_handler");
$i = 0;
while ($i++ 20){
$child++;
$pid=pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
// we are the parent
if ( $child >= $max ){
pcntl_wait($status);
}
} else {
// we are the child
echo "\t Starting new child | now we de have $child child processes\n";
// presumably doing something interesting
sleep(1);
exit;
}
}
//理论上fork时$child++,子进程死的是否$child--,那么子进程都退出时,$child应该为0,实际上$child是不确定的,我们可能永远看不到over
while($child > 0){
echo "wait_ret:".pcntl_wait($status)."\n";
echo "child:".$child."\n";
}
echo "over\n";
?>
似乎比较靠谱的做法是在pcntl_wait($status)后面$child--;这样程序肯定是可以正常终止的。至于为什么上面的程序为什么那样,我头疼的很哟!!!
相关阅读 更多 +