如何使用proc_open从仅打开一次的文件中获取多个结果?

时间:2015-09-25 18:52:54

标签: php proc-open

我有一个使用exec()运行的命令,它从一个非常大的数据文件中返回一个值,但它必须运行数百万次。为了避免每次在循环中打开文件,我想转移到基于proc_open的解决方案,其中文件指针创建一次以提高效率,但无法解决如何执行此操作。

这是基于exec的版本,虽然有效但速度很慢,可能是因为它必须在每次迭代中打开文件:

foreach ($locations as $location) {
    $command = "gdallocationinfo -valonly -wgs84 datafile.img {$location['lon']} {$location['lat']}";
    echo exec ($command);
}

我对基于proc_open的代码的尝试如下:

$descriptorspec = array (
    0 => array ('pipe', 'r'),  // stdin - pipe that the child will read from
    1 => array ('pipe', 'w'),  // stdout - pipe that the child will write to
    // 2 => array ('file', '/tmp/errors.txt', 'a'), // stderr - file to write to
);

$command = "gdallocationinfo -valonly -wgs84 datafile.img";
$fp = proc_open ($command, $descriptorspec, $pipes);

foreach ($locations as $location) {
    fwrite ($pipes[0], "{$location['lon']} {$location['lat']}\n");
    fclose ($pipes[0]);
    echo stream_get_contents ($pipes[1]);
    fclose ($pipes[1]);
}

proc_close ($fp);

这正确获取第一个值,但随后为每个后续迭代生成错误:

3.3904595375061 

Warning: fwrite(): 6 is not a valid stream resource in file.php on line 11
Warning: fclose(): 6 is not a valid stream resource in file.php on line 12
Warning: stream_get_contents(): 7 is not a valid stream resource in file.php on line 13
Warning: fclose(): 7 is not a valid stream resource in file.php on line 14

Warning: fwrite(): 6 is not a valid stream resource in file.php on line 11
...

1 个答案:

答案 0 :(得分:0)

  1. 您不是在“打开文件”而是在执行某个流程。如果该流程不是为处理单个执行范围内的多个请求而设计的,那么您将无法使用proc_open()或其他任何内容解决此问题。
  2. 在下面的块中,您关闭了流程的输入和输出管道,但是当您无法再读取或写入时,您会感到惊讶吗?

    foreach ($locations as $location) {
        fwrite ($pipes[0], "{$location['lon']} {$location['lat']}\n");
        fclose ($pipes[0]); // here
        echo stream_get_contents ($pipes[1]);
        fclose ($pipes[1]); // and here
    }
    

    尝试这样做。