给所有的shell程序全加上timeout参数

有些程序自带–timeout参数,比如rsync,这样很好。
但是有些程序就很不乖,比如ffmpeg,自己不会超时退出,这很不好。

让我们用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;

然后如下就可以让任意的命令超时退出了(这里执行的命令是“sleep 500”)

./timeout.pl --timeout=3 sleep 500

还没有评论,快来抢沙发!

发表评论

  • 😉
  • 😐
  • 😡
  • 😈
  • 🙂
  • 😯
  • 🙁
  • 🙄
  • 😛
  • 😳
  • 😮
  • emoji-mrgree
  • 😆
  • 💡
  • 😀
  • 👿
  • 😥
  • 😎
  • ➡
  • 😕
  • ❓
  • ❗
  • 70 queries in 0.380 seconds