PHP proc_open多次打开

Chr*_*ian 8 php windows proc-open command-line-interface k2f

我有一个实用程序函数用于通过CLI(cmd,bash等)执行程序.它返回的3项的数组:STDOUT,STDERREXIT 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 );
}
Run Code Online (Sandbox Code Playgroud)

注意注释行(第9行).那是为了测试.我启用它以确保目标程序只运行一次(我以为我的代码可能会以某种方式调用相同的函数).但即使启用该行,程序仍会运行多次.

实际上,我在我的代码中有两个位置,我正在执行相同的程序(在不同的场合).两个命令行都是相同的.

但是,有一次,程序运行一次,而在这种情况下,PHP运行程序3次.

我一直在Process Explorer下监视和看到这种行为.我使用的是Windows 7 x64.该程序是32位,PHP也是如此.

编辑:有问题的程序是自定义开发的,它不会打开新进程.

Byr*_*ock 1

用于测试它仅运行一次的代码看起来有缺陷。

如果您有 2 个 php 进程正在运行,它们将不会共享静态变量。因此,您可能有并发请求,导致其运行多次。

其次,您应该$once在函数末尾设置为 false,否则将die永远不会到达。

尝试添加一些日志记录以查看该函数是否被调用两次。

创建一些仅运行外部应用程序的单元/压力测试。如果您看到多个进程,那么您的应用程序有问题,而不是 php 代码。