PHP多进程并行处理任务

<?php
shell_exec('split -l 25000 -d file.log prefix_name');
// 3个子进程处理任务
for ($i = 0; $i < 3; $i++){   
 $pid = pcntl_fork();    
 if ($pid == -1) {
    die("could not fork");
} elseif ($pid) { 
     echo "I'm the Parent $i\n";
 } else {// 子进程处理
  $content = file_get_contents("prefix_name0".$i); 
// 业务处理 begin
// 业务处理 end
    exit;
// 一定要注意退出子进程,否则pcntl_fork() 会被子进程再fork,带来处理上的影响。    }
}// 等待子进程执行结束
while (pcntl_waitpid(0, $status) != -1) {    
$status = pcntl_wexitstatus($status);    
echo "Child $status completed\n";}
下面测试
<?php
$arr=array(1,2,3,44);
$pid_arr=array();
for($i=0;$i<4;$i++){
$pid=pcntl_fork();
if($pid==-1){
        die('could not fork');
}else if($pid){
     echo 'fzc'.$pid;
        $pid_arr[]=$pid;
//    pcntl_wait($status);
}else{
 echo 'z'.$pid.'___'.$i;
sleep(20);
$arr[]=$i+100;
print_r($arr);
echo 'end';
exit;
}

}
while(pcntl_waitpid(0,$status) != -1){
$status=pcntl_wexitstatus($status);
echo "child $status completed\n";
}

print_r($arr);
print_r($pid_arr);
posted @ 2020-04-25 18:13  yonomo  阅读(108)  评论(0)    收藏  举报