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


How do I get multiple results from a file opened only once using 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
...
    你不是在"打开一个文件",你在执行一个进程。如果该进程不是设计为处理单个执行范围内的多个请求,那么您将无法使用proc_open()或其他任何东西来解决这个问题。
  1. 在下面的代码块中,您关闭了进程的输入和输出管道,但是当您不再能够读取或写入时,您感到惊讶吗?

    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
    }
    

    试试不要那样做