如何在php中加入forked进程

时间:2012-11-19 13:34:09

标签: php fork pcntl

我需要在哪里分叉一个进程。然后当他们的任务完成时,父进程应继续进行其他工作。如何才能做到这一点?这就是我所做的

$sql = "call some_sample_proc()";
$res = $dbConn->query($sql);
$i=0;
$memcacheData = array();
while($row = $dbConn->fetch_assoc()) {
    $value = $row['col1'].$row['col2'].$row['col3'];
    $memcachceData[$i++] = $value;
}
for($i=0; $i<5; $i++) {
    $pid = pcntl_fork();
    if($pid == 0) {
        $im = $i;
        echo "forked process $i \n";   //  -- 1
        exit;
    } else if($pid == -1) {
        echo "Could not fork \n";
    }
}
while (pcntl_waitpid(0, $status) != -1) {
    $status = pcntl_wexitstatus($status);
    echo "Child $status completed $im\n ";
    $childCompleteCount ++;
}
echo "completion count $childCompleteCount\n";
if($childCompleteCount == 5) {
     echo "All finished\n";
     //exit; //if this is uncommented, ONLY THEN the program finishes 
}

当我用这段代码执行程序时,我得到了这个输出......

forked process 0
forked process 1
forked process 3
forked process 2
forked process 4
Child 0 completed 0
Child 0 completed 0
Child 0 completed 0
Child 0 completed 0
Child 0 completed 0
completion count 5
All finished

但打印完成后,计数5程序似乎挂了。它没有返回提示。现在我们知道所有子(forked)进程都已完成,我们如何恢复进一步执行?

0 个答案:

没有答案