简体   繁体   中英

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

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 in order for the rest of the files to be processed.

Whats the best way best way to apply a timeout after which the parent script will kill the hung process?

At the moment I'm using:

foreach $file (@FILES) {
    $runResult = `mytool $file >> $file.log`;
}

But when mytool hangs after n seconds I'd like to be able to kill it and continue to the next file.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM