简体   繁体   English

PHP-Linux上的Ping执行挂起脚本

[英]PHP - Ping exec on Linux hangs script

I have a simple PHP script setup to check the status of my servers. 我有一个简单的PHP脚本设置来检查服务器的状态。 It uses a standard ping command, run via exec(). 它使用通过exec()运行的标准ping命令。

  • On Windows, the script works fine both when a server is online and when down. 在Windows上,无论服务器处于联机状态还是停机状态,脚本都可以正常工作。
  • On Linux, the script works when the server is online, but hangs when the server is down. 在Linux上,该脚本在服务器联机时起作用,但在服务器关闭时挂起。 Timeout seems to have no effect on the latter. 超时似乎对后者没有影响。

Pinging with the same command via console works fine and times out correctly. 通过控制台使用同一命令ping可以正常工作并正确超时。


What's the cause, and how would this be fixed? 原因是什么,如何解决?

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  $exec_string = 'ping -n 1 -i 255 -w 2 ' . $host;
} else {
  $exec_string = 'ping -n -c 1 -t 255 -w 2 ' . $host;
}
exec($exec_string, $output, $return);

I would avoid pinging directly using an exec() . 我会避免直接使用exec() ping操作。 I use this script, found here , you can also setup port and timeout: 我使用此脚本, 位于此处 ,还可以设置端口和超时:

function ping($host, $port = 80, $timeout = 6) {
    $fsock = fsockopen($host, $port, $errno, $errstr, $timeout);
    if (!$fsock) {
        return false;
    } else {
        return true;
    }
}

$host = 'www.example.com';

if(ping($host)) {
    echo "HOST UP";
} else {
    echo "HOST DOWN";
}

I'm unsure why, but switching from suPHP to fastCGI (both with suEXEC enabled) seemed to resolve the issue and the ping properly times out as expected. 我不确定为什么,但是从suPHP切换到fastCGI(都启用了suEXEC)似乎可以解决该问题,并且ping可以按预期正确地超时。

If anyone has an explanation for this, I would love to know, in either comment or answer format. 如果有人对此有解释,我想知道以评论或答案的形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM