How can I specify timeout limit for Perl system call?

后端 未结 4 366
花落未央
花落未央 2020-12-24 06:28

Sometimes my system call goes into a never ending state. To, avoid that I want to be able to break out of the call after a specified amount of time.

Is there a way t

4条回答
  •  时光取名叫无心
    2020-12-24 07:22

    I've just used the timeout command in Perl + Linux before, something you can test like this:

    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";
    }
    

    Output after 4.317 seconds:

    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
    

    The timeout command is part of all major "normal" Linux distributions a.f.a.i.k, a part of coreutils.

提交回复
热议问题