php實現連續ping遠程服務器腳本

jopen 9年前發布 | 1K 次閱讀 PHP

腳本作用:持續ping該類服務器,保證中轉路由能在業務使用時能夠快速響應請求。

    <?php
define('LOGTAG', 'ping');
declare(ticks = 1);
$pid_arr = array();
pcntl_signal(SIGQUIT, 'signal_handler');
pcntl_signal(SIGTERM, 'signal_handler');

function run($servers_info)   
{  
    echo "---------- ping task begin ----------";  
    global $pid_arr;  
    $index=0;  
    $name_arr = array();  
    $ip_arr = array();  
    foreach( $servers_info as $val) {  
        $name_arr[$index] = $val['server_name'];  
        $ip_arr[$index] = $val['server_ip'];  
        $index++;  
    }  
    $worker_count = $index;  
    $index=0;  
    while($index < $worker_count)   
    {  
        $pid = pcntl_fork();  
        if($pid == -1) {  
            die('could not fork');  
        }   
        else   
        {  
            if($pid) {  
                $pid_arr[$index] = $pid;  
            } else {  
                while(true) {  
                    handle($name_arr[$index], $ip_arr[$index]);  
                    sleep(1);  
                }  
            }  
        }  
        $index++;  
    }  
    while (true) {  
        sleep(1);  
    }  
}  

function handle($name,$ip) {  
    echo "ping ".$name." ip:".$ip." start!";  
    exec("ping -c 1000 $ip",$list);  
    echo "ping ".$name." ip:".$ip." finish!";  
}  

function signal_handler($signal) {  
    global $pid_arr;  
    if ($signal == SIGQUIT || $signal == SIGTERM)   
    {  
        foreach ($pid_arr as $pid) {  
            posix_kill($pid,SIGTERM);  
        }  
        echo ”————— ping task finish ----------";  
        exit();  
    }  
}  

run();  
?>  </pre> 


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!