John Chrysostom
John Chrysostom

Reputation: 3983

PHP popen pipes becoming null after one iteration

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("\r\nStarted 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?

Upvotes: 2

Views: 117

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79014

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';
}

Upvotes: 2

Related Questions