简体   繁体   English

如何在不使分叉进程超时的情况下杀死在perl脚本中花费太长时间的分叉进程?

[英]How can I kill forked processes that take too long in my perl script without timing out the forked process?

I've been using the following template for all of my forking/processes needs when it comes to processing "things" in parallel. 在并行处理“事物”时,我一直在使用以下模板满足所有分叉/处理需求。 It basically loops through everything I need to process, X number of entries at a time, and time's out any entries that take too long: 它基本上遍历了我需要处理的所有内容,一次X个条目,并且超时了所有花费太长时间的条目:

my $num_procs = 0;
foreach my $entry (@entries) {
  $num_procs++;
  if($num_procs == $MAX_PROCS) {
    wait();
    $num_procs--;
  }
  my $pid = fork();
  if($pid == 0) {
    process($entry);
  } 
}
for (; $num_procs>0; $num_procs--) {
  wait();
}

The "process" routine has the following template which times out the process: “流程”例程具有以下模板,该模板会使流程超时:

my $TIMEOUT_IN_SECONDS = 15;
eval {
  local $SIG{ALRM} = sub { die "alarm" };
  alarm($TIMEOUT_IN_SECONDS);       

  # do something

  alarm(0);
};
if ($@) {
  # do something about the timeout
}   

I've now come across an issue where this no longer works because the child is unable to time itself out. 我现在遇到了一个问题,该问题不再起作用,因为孩子无法超时。 (I think this is due to an I/O blocking issue with NFS) The only way around this, I'm thinking, is for the parent itself to kill -9 the child. (我认为这是由于NFS的I / O阻塞问题造成的)我认为,解决此问题的唯一方法是让父母自己杀死-9个孩子。

Is there a way to modify my code to do this? 有没有办法修改我的代码来做到这一点?

Whenever alarm can be flaky, it is a good use case for the poor man's alarm : 每当alarm可能不稳定时,这都是穷人警报的一个好用例:

my $pid = fork();
if ($pid == 0) {
    ...  # child code
    exit;
}
if (fork() == 0) {
    my $time = 15;
    exec($^X, "-e", "sleep 1,kill(0,$pid)||exit for 1..$time;kill -9,$pid");
    die; # shouldn't get here 
}

The first fork fires off your child process. 第一个fork触发您的子进程。 The second fork is for running a process to kill the first process after $time seconds. 第二个fork用于运行一个进程,以在$time秒后终止第一个进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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