我只是想知道是否有可能检测到当前正在运行的脚本的执行时间,我正在创建一个应用程序来ping网络上的一些计算机。由于这是在Linux机器上完成的,所以点击系统不同于Windows。
在linux机器上,如果计算机关闭,那么在发出ping命令后,服务器将挂在主消息上,不再有任何输出。只会挂起(根据我对linux的经验)
所以我有个剧本:
$Computer_Array = array(
"Managers" => "192.168.0.5",
"Domain Controller" => "192.168.0.1"
"Proxy Controller" => "192.168.0.214"
);
foreach ($Computer_Array AS $Addresses){
exec('ping'.$Addresses, $Output);
}稍后将用于显示统计数据。现在的问题是,由于管理人员的计算机在发出ping命令时受到开关等两种电源条件的影响,所以只能挂起。因此,我想知道是否有一种方法来捕获当前执行函数的microtime();,如果它超过了阈值,那么就转到下一个元素。我宁愿把它留给核心PHP,但是如果这样的解决方案只能通过AJAX或另一种语言完成,那么如果集成外部方法是可以的,那么我必须咨询开发人员。
发布于 2013-05-17 00:21:23
ping命令允许您指定在放弃之前需要等待多长时间:
ping -c 5 -t 1 127.0.0.2这将在1秒后返回,不管已经发送了多少pings。具体的命令行参数将因平台而异。
或者,如果您可以使用pcntl,请查看pcntl_alarm();它将在一定时间后将SIGALRM信号传递给您的应用程序。
最后,我自己还没有测试过这一点,您可以尝试在其中一个管道上使用proc_open()并使用stream_select();如果在一定时间后管道上没有发生任何事情,那么您就可以终止该进程。
发布于 2013-05-17 00:20:16
如果您想用PHP来做这件事,或者遇到类似的问题,下面是一个使用php execute a background process代码的例子
PHP脚本需要对输出文件具有写权限。这个概念基本上适用于任何东西,从ping到另一个PHP脚本。
function isRunning($pid){
try{
$result = shell_exec(sprintf("ps %d", $pid));
if( count(preg_split("/\n/", $result)) > 2){
return true;
}
}catch(Exception $e){}
return false;
}
$cmd = "ping 127.0.0.1";
$outputfile = "output";
$pidfile = "pid";
$start = microtime(true);
// Don't last longer than 10 seconds
$threshold = 2;
// Ping and get pid
exec(sprintf("%s > %s 2>&1 & echo $! > %s", $cmd, $outputfile, $pidfile));
$pid = `tail -n 1 $pidfile`;
// Let the process run until you want to stop it
while (isRunning($pid)){
// Check output here...
if ((microtime(true)-$start) > $threshold){
$o = `kill $pid`;
die("Timed out.");
}
}
$end = microtime(true);
$time = $end - $start;
echo "Finished in $time seconds\n";https://stackoverflow.com/questions/16599211
复制相似问题