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';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?