我正在使用我编写的包装器类运行第三方脚本,该包装器类调用 shell_exec()
并通过管道传输到我稍后使用 php 代码解析的文件中。我应该提到这是有效的,但我正在尝试增强功能,遇到了一个我没有想到的用例。
如何最好地管理 shell_exec() 的超时?我正在考虑将它包装在 try() catch()
中,但我不确定如何最好地处理时间组件。
我在这里阅读了一些与 shell_exec()
和 exec()
相关的问题,似乎通过将输出参数传递给 exec( )
您可以获得返回,但这确实依赖于脚本以返回状态结束。另外,在我的迷你测试页面中,我似乎无法让它返回任何输出!
我想到的另一个选择是使用模式对话框,在脚本运行时使用 ajax 样式的微调器,并在 javascript 中设置手动超时。然后向用户提供有关失败/超时和结束的模型对话框消息。
这个用例是否有任何可接受的方法?
我的迷你测试包括以下内容,
public $e_return = array();
public $e_status = '';
// Paths are absolute from /
public function execCheck($domain){
exec($this->ssl_check_path." -s ".$domain." -p 443 > ".$this->folder.$this->filename." 2>&1 &", &$this->e_return, &$this->e_status);
}
// Returns
Array
(
)
0
使用这个问题作为引用, Can't execute PHP script using PHP exec
最佳答案
我为这样的任务写了一些工作代码。函数返回退出代码(0 - OK,>0 - 错误)并将 stdout、stderr 写入引用变量。
/*execute program and write all output to $out
terminate program if it runs more than 30 seconds */
execute("program --option", null, $out, $out, 30);
echo $out;
function execute($cmd, $stdin=null, &$stdout, &$stderr, $timeout=false)
{
$pipes = array();
$process = proc_open(
$cmd,
array(array('pipe','r'),array('pipe','w'),array('pipe','w')),
$pipes
);
$start = time();
$stdout = '';
$stderr = '';
if(is_resource($process))
{
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
fwrite($pipes[0], $stdin);
fclose($pipes[0]);
}
while(is_resource($process))
{
//echo ".";
$stdout .= stream_get_contents($pipes[1]);
$stderr .= stream_get_contents($pipes[2]);
if($timeout !== false && time() - $start > $timeout)
{
proc_terminate($process, 9);
return 1;
}
$status = proc_get_status($process);
if(!$status['running'])
{
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
return $status['exitcode'];
}
usleep(100000);
}
return 1;
}
关于php - shell_exec() 超时管理 & exec(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3407939/