我有以下PHP脚本。我需要用5个子进程(使用pcntl_fork()函数)执行5个不同的任务。孩子们被正确地创造出来,他们做自己的事情,但他们似乎永远不会离开。父母等着他们结束,但从来没有发生过。有人能告诉我我做错了什么吗?
<?php
for ($i=1; $i<=5; $i++) {
$pid = pcntl_fork();
if ($pid == -1) {
die("Error Creating subprocess ".$i);
exit(-1);
}
else if (!$pid) {
switch ($i) {
case 1:
// Child 1
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 2:
// Child 2
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 3:
// Child 3
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 4:
// Child 4
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 5:
// Child 5
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
default:
break;
}
}
else {
$pids[] = $pid;
}
}
error_log("Luke, I''m your father. PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
foreach ($pids as $key => $child) {
$res = pcntl_waitpid($child, $status);
//Check if this child has exited normally
if (pcntl_wifexited($status))
error_log("Child ".$child." has ended'n", 3, "/var/log/php_errors.log");
else
error_log("Child ".$child." is zombie'n", 3, "/var/log/php_errors.log");
if($res == -1 || $res > 0)
unset($pids[$key]);
}
?>
<?php
for ($i=1; $i<=5; $i++) {
$pid = pcntl_fork();
if ($pid == -1) {
die("Error Creating subprocess ".$i);
exit(-1);
}
else if (!$pid) {
switch ($i) {
case 1:
// Child 1
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 2:
// Child 2
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 3:
// Child 3
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 4:
// Child 4
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
case 5:
// Child 5
error_log("I''m the child number ".$i." PID: ".getmypid()."'n", 3, "/var/log/php_errors.log");
//Doing some stuff
exit;
default:
break;
}
}
else {
$pids[$pid] = $pid;
}
}
while (!empty($pids)) {
if ($child = pcntl_wait($status, WNOHANG)) {
if (pcntl_wifexited($status))
error_log("Child ".$child." has ended'n", 3, "/var/log/php_errors.log");
else
error_log("Child ".$child." is zombie'n", 3, "/var/log/php_errors.log");
unset($pids[$child]);
} else
usleep(100);
}
别忘了把$pids[]改成$pid;到$pid[$pid]=$pid;:o) 或者选择更好的方式从数组退出的子项中弹出。