How can I kill a Perl system call after a timeout?

后端 未结 2 1394
失恋的感觉
失恋的感觉 2021-01-21 08:15

I\'ve got a Perl script I\'m using for running a file processing tool which is started using backticks. The problem is that occasionally the tool hangs and It needs to be killed

相关标签:
2条回答
  • 2021-01-21 08:44

    You need to set $SIG{'ALRM'} to a handler routine and then call the alarm function with the timeout value. Something like:

    $SIG{'ALRM'} = handler;
    foreach $file (@FILES) {
      alarm(10);
      $runResult = `mytool $file >> $file.log`;
      alarm(0);
    }
    
    sub handler {
      print "There was a timeout\n";
    }
    

    This should trigger the handler subroutine after 10 seconds. Setting alarm to 0 turns off the alarm.

    0 讨论(0)
  • 2021-01-21 08:50

    I would probably not use `` for this. Instead I would open() the command with | so that it runs asynchronously. This will return the pid. Then you can do a nonblocking wait() in a loop with sleep that after a certain number of tries without success, issues a signal to the child pid.

    0 讨论(0)
提交回复
热议问题