有关perl程序执行超时的处理办法

2839阅读 0评论2012-03-19 努力小伙
分类:Python/Ruby

MicrosoftInternetExplorer402DocumentNotSpecified7.8Normal0

这里利用ALRM信号。注意一点是eval中的die只会退出eval块并将原因保存在$@中,后续程序通过检测$@来做出更有意思的决定。


点击(此处)折叠或打开

  1. # 超时处理
  2. # 来源: Lover的工具小屋
  3. # author: Lover

  4. local $SIG{ALRM} = sub {alarm 0;die 'TIMEOUT';};
  5. my $timeout = 3;
  6. eval{
  7.         alarm $timeout;
  8.         #一个类似linux shell窗口中的提示符
  9.         print("[root\@$target ~]# $command\n");
  10.         #实例化一个$pssh对象用于远程执行命令
  11.         my $pssh = Net::OpenSSH::Parallel->new   (reconnections=>2,connections=>90,workers=>45);
  12.                 $pssh->add_host("root\@$target");
  13.                 $pssh->push('*',command=>$command);
  14.         my $status = $pssh->run;

  15.         if ($status != 1){
  16.                 print("[root\@$target]# $command\n");
  17.                 die "Command Exec Error: $!";
  18.         }
  19.         # 如果之前的代码在规定的时间内执行完毕,排除这个定时炸弹
  20.         alarm(0);
  21. };

  22. if ($@ =~ /TIMEOUT/){
  23.         die 'Execute Command Timeout';
  24. }

上一篇:Net::Ping模块实现自己的主机存活检测工具
下一篇:使用strftime返回可读的时间格式