douque8855 2015-01-22 19:03
浏览 89
已采纳

PHP popen管道在一次迭代后变为null

I'm trying to generate 12 worker processes to work on various chunks of my data using popen in PHP under Windows. Here's my code... it's pretty generic.

<?php
    set_time_limit(0);

    $workers = array_fill(0, 12, null);

    $currChunk = 56;
    $working = true;

    while($working == true) {
        $working = false;

        foreach($workers as $worker) {
            if($worker == null) {
                if($currChunk < 265) {
                    $worker = popen('C:\php\php.exe "C:\users\administrator\desktop\do one chunk.php" '.$currChunk, 'r');
                    echo("
Started a worker on chunk ".$currChunk);
                    $currChunk ++;

                    $working = true;
                }
            } else {
                if(feof($worker)){
                    pclose($worker);
                    $worker = null;
                    echo("A worker finished!");
                } else {
                    fread($worker, 1);

                    $working = true;
                }
            }
        }

        sleep(.01);
    }
?>

What's happening here is that the script just continually starts new workers until it hits the limit of 265, then it ends. It never waits for them to actually finish.

I've tried echoing the value of $worker after the popen and I get back "Resource Instance ID #XXX" which tells me that's working fine.

I've also tried echoing "here!" for the else section of code that should execute if the worker is not set to null... that code never executes, even though it should.

What's up? Am I blind?

  • 写回答

1条回答 默认 最新

  • douyong4842 2015-01-22 19:27
    关注

    foreach operates on a copy of the array. You need to reference $worker using & to modify the elements of the original array:

    foreach($workers as &$worker) {
    

    The alternative is:

    foreach($workers as $key => $worker) {
        $workers[$key] = 'something';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?