代码之家  ›  专栏  ›  技术社区  ›  Aakash Goel

如何指定Perl系统调用的超时限制?

  •  27
  • Aakash Goel  · 技术社区  · 15 年前

    有时我的系统调用会进入一个永不结束的状态。为了避免我想在一段指定的时间后中断通话。

    是否有方法将超时限制指定为 system ?

    system("command", "arg1", "arg2", "arg3");
    

    为了便于移植,我希望在Perl代码中实现超时,而不是使用某些特定于操作系统的函数,比如ulimit。

    4 回复  |  直到 15 年前
        1
  •  28
  •   AndyG    8 年前

    alarm 功能。pod示例:

    eval {
        local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
        alarm $timeout;
        $nread = sysread SOCKET, $buffer, $size;
        alarm 0;
    };
    if ($@) {
        die unless $@ eq "alarm\n";   # propagate unexpected errors
        # timed out
    }
    else {
        # didn't
    }
    

    在CPAN上有一些模块可以更好地包装这些内容,例如: Time::Out

    use Time::Out qw(timeout) ;
    
    timeout $nb_secs => sub {
      # your code goes were and will be interrupted if it runs
      # for more than $nb_secs seconds.
    };
    
    if ($@){
      # operation timed-out
    }
    
        2
  •  14
  •   ysth    15 年前

    IPC::Run 的运行方法,而不是系统。并设置超时。

        3
  •  3
  •   melpomene    9 年前

    怎么样 System::Timeout ?

    此模块扩展 system

    timeout("3", "sleep 9"); # timeout exit after 3 seconds
    
        4
  •  1
  •   Kjetil S.    7 年前

    我刚刚用了 timeout 命令在Perl+Linux之前,您可以这样测试:

    for(0..4){
      my $command="sleep $_";  #your command
      print "$command, ";
      system("timeout 1.1s $command");  # kill after 1.1 seconds
      if   ($? == -1  ){ printf "failed to execute: $!" }
      elsif($?&127    ){ printf "died, signal %d, %scoredump", $?&127, $?&128?'':'no '}
      elsif($?>>8==124){ printf "timed out" }
      else             { printf "child finished, exit value %d", $? >> 8 }
      print "\n";
    }
    

    4.317秒后输出:

    sleep 0, child finished, exit value 0
    sleep 1, child finished, exit value 0
    sleep 2, timed out
    sleep 3, timed out
    sleep 4, timed out
    

    这个 超时