【发布时间】:2011-01-23 20:38:17
【问题描述】:
我有一个用于通过 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 也是。
编辑:有问题的程序是自定义开发的,它不会打开新进程。
【问题讨论】:
-
使用另一个过程工具来验证观察结果。您没有提到它是什么程序(可能会自行分叉到子进程中)。
-
@Christian:我们如何检查它?正如你所说,你没有提到它是什么程序。马里奥是完全正确的;你应该听他的。
-
对不起,我的意思是“检查过”(我现在删除了评论以避免混淆)。我(的意思)是我用进程监视器检查了它。编辑:我确实听他的;)大声笑
-
您能否为我们提供逐个案例的示例,以及每个案例的脚本执行多少次?确保还记下您执行脚本的时间。我担心即使输入相同,重复也会有所不同。
-
你可以使用类似flock() php.net/manual/en/function.flock.php的东西来确保它只运行一次。
标签: php windows command-line-interface proc-open k2f