我有一个使用 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
...