如何使可能挂起的分支过程超时? [英] How can I timeout a forked process that might hang?

查看:75
本文介绍了如何使可能挂起的分支过程超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Perl脚本,它将编写一些输入并将这些输入发送到外部程序。该程序挂起的可能性很小,但非零,我想超时:

I am writing a Perl script that will write some inputs and send those inputs to an external program. There is a small but non-zero chance that this program will hang, and I want to time it out:

my $pid = fork;
if ($pid > 0){
    eval{
        local $SIG{ALRM} = sub { die "TIMEOUT!"};
        alarm $num_secs_to_timeout;
        waitpid($pid, 0);
        alarm 0;
    };
}
elsif ($pid == 0){
    exec('echo blahblah | program_of_interest');
    exit(0);
}

就目前情况而言,在$ num_secs_to_timeout之后,program_of_interest仍然存在。我尝试在 $ SIG {ALRM} 的匿名子例程中杀死它,如下所示:

As it stands now, after $num_secs_to_timeout, program_of_interest still persists. I tried to kill it in the anonymous subroutine for $SIG{ALRM} as follows:

local $SIG{ALRM} = sub{kill 9, $pid; die "TIMEOUT!"}

但这没有任何作用。 program_of_interest仍然存在。我该如何终止该进程?

but this doesn't do anything. program_of_interest is still persisting. How do I go about killing this process?

推荐答案

我能够通过成功终止我的exec()处理过的进程杀死进程组,如问题在perl中,使用open创建孩子时会杀死孩子及其孩子。。我将代码修改如下:

I was able to successfully kill my exec()ed process by killing the process group, as shown as the answer to question In perl, killing child and its children when child was created using open. I modified my code as follows:

my $pid = fork;
if ($pid > 0){
    eval{
        local $SIG{ALRM} = sub {kill 9, -$PID; die "TIMEOUT!"};
        alarm $num_secs_to_timeout;
        waitpid($pid, 0);
        alarm 0;
    };
}
elsif ($pid == 0){
    setpgrp(0,0);
    exec('echo blahblah | program_of_interest');
    exit(0);
}

超时后,program_of_interest被成功杀死。

After timeout, program_of_interest is successfully killed.

这篇关于如何使可能挂起的分支过程超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆