主程序
<?php
$childs = array();
$cmds=array(
array('/root/sub.php','120'),
array('/root/sub.php','120'),
array('/root/sub.php','120'),
array('/root/sub.php','120'),
array('/root/sub.php','120'),
array('/root/sub.php','120')
);
echo 'begin';
echo date("Y-m-d H:i:s");
foreach($cmds as $cmd){
$pid=pcntl_fork();
if($pid==-1){ //进程创建失败
die('fork child process failure!');
}
else if($pid){ //父进程处理逻辑
$childs[] = $pid;
pcntl_wait($status,WNOHANG);
}
else{ //子进程处理逻辑
pcntl_exec('/usr/bin/php',$cmd);
}
}
while (count($childs) > 0) {
foreach ($childs as $key => $pid) {
$res = pcntl_waitpid($pid, $status, WNOHANG);
//-1代表error, 大于0代表子进程已退出,返回的是子进程的pid,非阻塞时0代表没取到退出子进程
if ($res == -1 || $res > 0)
unset($childs[$key]);
}
sleep(1);
}
echo date("Y-m-d H:i:s");
echo 'done';
?>
子程序
<?php
echo $argv[1];
sleep ($argv[1]);
?>