可以设置命令执行的超时时间的脚本

旧博客第三弹:

在linux下,执行程序时,有一个需求就是在一定的时间内执行完成,未执行完成则退出。下面是工作中经常使用的一个perl程序,可以设置超时,通过alarm信号机制进行控制

执行命令 ./timeout.pl -c command -t timeout

eg: ./timeout.pl -c "./run.sh" -t 180

#!/usr/bin/perl -w
use strict;
use Getopt::Std;
my $result;
my % opts;
getopt('ct', /%opts);
sub ss_h(){
        eval {
                local $SIG{ALRM} = sub{die "alarm/n"};
                alarm $opts{'t'};
                #$result=`$opts{'c'}`;
                system($opts{'c'});
                $result = $?;
                alarm 0;
        };
        if ($@ and $@ =~ /alarm/) {
                kill('INT', $);
                exit (1);
        } elsif ( $result == 0 ){
                exit (0);
        }else {
                exit (1);
        }
}
&ss_h();
原文地址:https://www.cnblogs.com/wully/p/3341332.html