我有一个实用程序函数,用于通过 CLI(cmd、bash 等)执行程序。它返回一个包含 3 个项目的数组STDOUT
:STDERR
和EXIT CODE
。
到目前为止,它运行良好,没有任何问题。事实上,我遇到的问题并没有真正阻碍它的功能,但我担心性能。
问题是在某些情况下,PHP 多次运行相同的命令(在我的情况下为 3 次),即使它应该只执行一次。
/**
* Executes a program and waits for it to finish, taking pipes into account.
* @param string $cmd Command line to execute, including any arguments.
* @param string $input Data for standard input.
* @param boolean $log Whether to log execution failures or not (defaults to true).
* @return array Array of "stdout", "stderr" and "return".
*/
public static function execute($cmd,$stdin=null,$log=true){
//static $once=true; if(!$once)die; $once=false;
$proc=proc_open($cmd, array(
0=>array('pipe','r'),
1=>array('pipe','w'),
2=>array('pipe','w') ), $pipes);
fwrite($pipes[0],$stdin); fclose($pipes[0]);
$stdout=stream_get_contents($pipes[1]); fclose($pipes[1]);
$stderr=stream_get_contents($pipes[2]); fclose($pipes[2]);
$return=proc_close($proc);
if($return!=0 && $log)
xlog('Error: Program execution returned failure.',$stdout,$stderr,$return);
return array( 'stdout'=>$stdout, 'stderr'=>$stderr, 'return'=>$return );
}
注意注释行(第 9 行)。那是为了测试。我启用它以确保目标程序只运行一次(我在想我的代码可能会以某种方式调用相同的函数)。但即使启用了该行,该程序仍会运行多次。
事实上,我的代码中有两个地方正在执行相同的程序(在不同的场合)。它们的命令行是相同的。
但是,有一次,程序运行一次,而在这种情况下,PHP 运行了 3 次。
我一直在 Process Explorer 下监视并查看此行为。我正在使用 Windows 7 x64。该程序是 32 位的,PHP 也是如此。
编辑:有问题的程序是定制开发的,它不会打开新流程。