我不是PHP的专家。我有一个使用EXEC运行WINRS的函数,然后在远程服务器上运行命令。问题是这个函数被放入一个调用getservicestatus函数几十次的循环中。有时WINRS命令会卡住或花费比预期更长的时间,导致PHP脚本超时并抛出500错误。PHP函数超时
暂时我已经降低了PHP中的设置超时值,并在IIS中创建了一个自定义的500页,如果引用页面等于脚本名称,然后重新加载页面(否则抛出错误)。但这很混乱。显然它不适用于每次调用该函数,因为它是全局的。所以它只会避免页面停止在HTTP 500错误。
我真的很想做的就是在函数本身上设置5秒的超时时间。我一直在搜索相当多的东西,甚至在stackoverflow上都找不到答案。是的,也有类似的问题,但我一直没有找到任何与我的功能相关的问题。也许有一种方法可以在执行命令时执行此操作,例如exec()的替代方法?我不知道。理想情况下,我希望该功能在5秒后超时并将$ servicestate返回为0.
代码被注释以解释我的意大利面条混乱。我很遗憾,你必须看到它......
function getservicestatus($servername, $servicename, $username, $password)
{
//define start so that if an invalid result is reached the function can be restarted using goto.
start:
//Define command to use to get service status.
$command = 'winrs /r:' . $servername . ' /u:' . $username . ' /p:' . $password . ' sc query ' . $servicename . ' 2>&1';
exec($command, $output);
//Defines the server status as $servicestate which is stored in the fourth part of the command array.
//Then the string "STATE" and any number is stripped from $servicestate. This will leave only the status of the service (e.g. RUNNING or STOPPED).
$servicestate = $output[3];
$strremove = array('/STATE/','/:/','/[0-9]+/','/\s+/');
$servicestate = preg_replace($strremove, '', $servicestate);
//Define an invalid output. Sometimes the array is invalid. Catch this issue and restart the function for valid output.
//Typically this can be caught when the string "SERVICE_NAME" is found in $output[3].
$badservicestate = "SERVICE_NAME" . $servicename;
if($servicestate == $badservicestate) {
goto start;
}
//Service status (e.g. Running, Stopped Disabled) is returned as $servicestate.
return $servicestate;
}
我相信你不能有'开始'那样的?你必须记得这个功能。 – Script47
可能。但是像这样实施它实际上解决了我遇到的问题之一。基本上,winrs命令的输出有时可能是无效的。我用$ badservicestate捕获并启动;。有用。但这并不意味着它是正确的。 – Cormang
问题在于exec()将会阻塞,直到命令完成,除非你调用的外部命令有一个自己的超时方法,否则你将不得不使用['proc_open()'' ](http://php.net/manual/en/function.proc-open.php)。 – Sammitch