gpt4 book ai didi

Perl fork 和kill - Kill(0, $pid) 总是返回1,并且不能杀死子进程

转载 作者:行者123 更新时间:2023-12-02 20:06:21 24 4
gpt4 key购买 nike

我正在 Linux 主机上运行 perl 脚本。我正在尝试编写一个 fork 脚本,其中子进程启动一个需要很长时间的程序,而父进程在 5 秒后超时,从而杀死了子进程。这是我所拥有的:

my $start = time();
my $timeOut = 5;

my $childPid = fork();
if ($childPid) {
# I am the parent, and $childPid is my child
while (kill(0, $childPid)) {
if (time() > $start + $timeOut) {
$numKilled = kill(SIGTERM, $childPid);
printf("numKilled: %s\n", $numKilled);
}
sleep 1;
}
}
else {
# I am the child - do something that blocks forever
`adb -s 410bf6c1 logcat`;
exit;
}

输出:

aschirma@graphics9-lnx:~$ perl perl-fork-test.pl 
numKilled: 1
numKilled: 1
numKilled: 1
numKilled: 1
numKilled: 1
...

我期望的行为是我只看到“numKilled: 1”一次,并且子进程(及其任何子进程)在大约 5 秒后被终止。但我从实验中看到, child 及其 child 都没有被杀死。 kill(SIGTERM, $childPid) 似乎什么也没做。

我怎样才能真正杀死 child ?

最佳答案

应该是这样的。这不遵循最佳实践,但它应该可以帮助您解决问题...

#!/usr/bin/perl

use warnings;
use strict;
use POSIX qw(:sys_wait_h);

my $timeOut = 5;
$SIG{ALRM} = \&timeout;
$SIG{CHLD} = 'IGNORE',
alarm($timeOut);

my $childPid = fork();
if ($childPid) {
while(1) {
print "[$$]: parent...\n";
sleep(2);
}
}else {
# I am the child - do something that blocks forever
while(1){
print "[$$]: child...\n";
sleep(2);
}
exit;
}

sub timeout {
print "killing $childPid\n";
print "###\n" . `ps -ef | grep -v grep | grep perl` . "###\n";
if ( ! (waitpid($childPid, WNOHANG)) ) {
print "killing $childPid...\n";
kill 9, $childPid;
die "[$$]: exiting\n";
}
}

输出:

$ forktest.pl
[24118]: parent...
[24119]: child...
[24118]: parent...
[24119]: child...
[24118]: parent...
[24119]: child...
killing 24119
###
cblack 24118 12548 0 14:12 pts/8 00:00:00 /usr/bin/perl ./forktest.pl
cblack 24119 24118 0 14:12 pts/8 00:00:00 /usr/bin/perl ./forktest.pl
###
killing 24119...
[24118]: exiting

关于Perl fork 和kill - Kill(0, $pid) 总是返回1,并且不能杀死子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15012289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com