我有以下代碼:PHP流程執行超時
/**
* 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
);
}
它有兩個 「問題」。
- 該代碼是同步的;它會凍結,直到目標進程關閉。
- 到目前爲止,我還沒有,而不會發出不同類型的命令能夠從「凍結」(如
$cmd > /dev/null &
在Linux和start /B $cmd
在Windows上)
我不介意「凍結「,完全可以。我只需要實現那個超時。
注意:該解決方案跨平臺兼容非常重要。 $cmd
不必更改也很重要 - 我運行的是一些複雜的命令,但恐怕可能會出現一些問題,但這取決於修復的類型 - 我很高興聽到這些信息,只是我更喜歡不同的選擇。
我發現一些資源,可以幫助:
- Run perl file from PHP script but not wait for output on Windows Server
- PHP set timeout for script with system call, set_time_limit not working
- http://www.shapeshifter.se/2008/08/04/asynchronous-background-execution-with-php/