我正在编写一个 Perl 脚本,它将写入一些输入并将这些输入发送到外部程序。该程序挂起的可能性虽小但非零,我想将其超时:
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}
如下:
local $SIG{ALRM} = sub{kill 9, $pid; die "TIMEOUT!"}
但这没有任何作用。 program_of_interest 仍然存在。我该如何杀死这个进程?
我能够通过以下方式成功终止我的 exec()ed 进程杀死进程组,如问题答案所示在perl中,当使用 open 创建子项时杀死子项及其子项 https://stackoverflow.com/questions/1675750/in-perl-killing-child-and-its-children-when-child-was-created-using-open/1675968#1675968。我修改了我的代码如下:
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被成功杀死。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)