歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> 解決shell、perl及ssh腳本中的超時問題

解決shell、perl及ssh腳本中的超時問題

日期:2017/3/3 16:28:21   编辑:關於Linux

大家有時候執行一個腳本,因為腳本中有些程序的假死和超時,影響了我們對下一步的判斷。隨意我們有必要設置對函數和進程的超時設置,讓他在一段時間沒有反應後,return一個狀態。

在命令參數裡ssh -o ServerAliveInterval=60 這樣子就能控制到60秒。

比如ClientAliveInterval=15,ClientAliveCountMax=3,那就會在15秒發送一次,30秒發送一次,45秒發送一次,如果三次都失敗,收回這個鏈接

但是這個參數不是太好用,大家可以後面加個 sleep 100 試試。

#!/bin/sh    

timeout()    
{    
        waitfor=3    
        command=$*    
        $command &    
        commandpid=$!    

        ( sleep $waitfor ; kill -9 $commandpid > /dev/null 2>&1 ) &    

        watchdog=$!    
        sleeppid=$PPID    
        wait $commandpid > /dev/null 2>&1     

        kill $sleeppid > /dev/null 2>&1    
}    

test123()    
{    

        ifconfig    
        sleep 10    
        ifconfig    
#        curl htpp://www.facebook.com    
}    

timeout test123

基本控制到 3s 左右

還有一個perl版本的

#! /usr/bin/env perl    
use POSIX qw(strftime WNOHANG);    

#check input    
my $timeout = shift @ARGV;    
my ($secs) = $timeout =~ /--timeout=(\d+)$/;    
unless($secs)    
{    
    print "Usage: ./timeout --timeout=[SECONDS] [COMMAND] \n";    
    exit -1;    
}    

#fork and exec    
my $status = 0;    
$SIG{CHLD} = sub { while(waitpid(-1,WNOHANG)>0){ $status = -1 unless $? == 0; exit $status;} };    
$0 = 'timeout hacked ' . $ARGV[0];    
defined (my $child = fork);    
if($child == 0)    
{    
    my $cmd = join ' ', @ARGV;    
    exec($cmd);    
}    
$SIG{TERM} = sub { kill TERM => $child };    
$SIG{INT} = sub { kill INT => $child };    


#kill when timeout    
sleep $secs;    
$status = -1;    
kill TERM => $child;    
sleep 1 and kill INT => $child if kill 0 => $child;    
sleep 1 and kill KILL => $child if kill 0 => $child;    
exit $status;    
#用法  ./t --timeout=3 curl http://www.facebook.com

上面是perl 其實用的方法是一樣的~

本文出自 “峰雲,就她了。” 博客,請務必保留此出處http://rfyiamcool.blog.51cto.com/1030776/1189520

Copyright © Linux教程網 All Rights Reserved