Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3015810
  • 博文数量: 535
  • 博客积分: 15788
  • 博客等级: 上将
  • 技术积分: 6507
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-07 09:11
文章分类

全部博文(535)

文章存档

2016年(1)

2015年(1)

2014年(10)

2013年(26)

2012年(43)

2011年(86)

2010年(76)

2009年(136)

2008年(97)

2007年(59)

分类: LINUX

2010-12-30 11:25:34

SIGALRM

Sent when the timer set by the alarm function expires (《perl cookbook》)


在perl中运行一些独立的程序时可能会挂起会处理较长时间,这种情况下可以使用alarm

#!/usr/bin/perl -W

$timeout=5;

eval {
        local $SIG{ALRM} = sub { die "$timeout second,run alarm\n" };#定义alarm运行的程序,这里设定为die并打印信息。
        alarm $timeout; #设定 5秒后进入超时处理
        sleep 20;
        print "in alarm eval\n";#因为5秒后会进入超时处理,die会中断eval块,所以这里并不会运行。

alarm (0); #所需的程序已经运行完成,取消超时处理

};

print "out of alarm eval\n"


#####后续处理

if ($@) {

    if ($@ =~ /die in sig alarm/) {

      print "caught the error";

    }

    else {

      print $@;

    }

  }

}



经过timeout时间,会进入超时处理,在上面的例子中,die会中断eval块的处理,但是不会结束整个程序,eval块以后的程序仍会运行,这就是为什么要使用eval的原因。

如果将sleep改为2,小于timeout时间,则不会进入超时处理,则eval块内的print也会运行。

Only one timer may be counting at once. Each call disables the previous timer, and an argument of 0 may be supplied to cancel the previous timer without starting a new one. 
同一时间只能有一个超时时间,每次调用alarm,取消前面的一个超时时间。alarm 0用于取消前一个超时时间,但不启动一个新的超时时间。

再一个例子,这里没有使用eval

$SIG{ALRM} = sub {
        system("killall -9 firefox") or warn "Fail to kill firefox process \n";
        print join '', time2str("[%Y-%m-%d %H:%M:%S] ", time), "Wait too long, kill the firefox process \n";
};


alarm 120; #120s后kill掉firefox进程。

system(“firefox”);

alarm 0; #取消超时处理


shell的超时处理

  1. timeout()
  2. {
  3.         waitfor=15
  4.         command=$*
  5.         $command &
  6.         commandpid=$!

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

  8.         watchdog=$!
  9.         sleeppid=$PPID
  10.         wait $commandpid > /dev/null 2>&1
  11.         kill $sleeppid > /dev/null 2>&1
  12. }


  13. echo "######Tail log for 15 seconds then exit tail"
  14. timeout "tail -f /etc/openvpn/log.vpn"


阅读(11333) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~