我有以下PHP脚本。我需要使用5个不同的子进程执行5个不同的任务(使用pcntl_fork()函数)。孩子们被正确创造并且他们做了他们的东西,但似乎他们永远不会退出。家长等他们结束但从未发生过。谁能告诉我我做错了什么?
<?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]);
}
?>
答案 0 :(得分:0)
<?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;到$ pids [$ pid] = $ pid; :o)或选择更好的方式从阵列退出的孩子弹出。