【发布时间】:2011-03-15 09:41:56
【问题描述】:
我有以下代码:
/**
* 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 integer $timeout How much to wait from program in msecs (-1 to wait indefinitely).
* @return array Array of "stdout", "stderr" and "return".
*/
function execute($cmd,$stdin=null,$timeout=-1){
$proc=proc_open(
$cmd,
array(array('pipe','r'),array('pipe','w'),array('pipe','w')),
$pipes=null
);
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);
return array(
'stdout' => $stdout,
'stderr' => $stderr,
'return' => $return
);
}
它有两个“问题”。
- 代码是同步的;它会冻结,直到目标进程关闭。
- 到目前为止,如果不发出不同类型的命令(例如 Linux 上的
$cmd > /dev/null &和 Windows 上的start /B $cmd),我就无法将其从“冻结”状态中解脱出来
我完全不介意“冻结”。我只需要实现那个超时。
注意:解决方案跨平台兼容很重要。 $cmd 不必更改也很重要 - 我正在运行一些复杂的命令,我担心可能会出现一些问题,但是,这取决于修复的类型 - 我很高兴听到这些,只是我更喜欢不同的选择。
我找到了一些可能有帮助的资源:
【问题讨论】:
标签: php process timeout proc-open