我在Linux主机上运行perl脚本。 我试图写一个脚本,分叉,孩子开始一个永久需要的程序,父母在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秒后终止。 但是我从实验中看到,孩子和孩子都没有死亡。 kill(SIGTERM, $childPid)似乎什么都不做。
我怎么能杀死孩子?
I am running a perl script on a Linux host. I'm trying to write a script that forks, where the child starts a program that takes forever and the parent times out after 5 seconds, killing the child. Here is what I have:
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; }Output:
aschirma@graphics9-lnx:~$ perl perl-fork-test.pl numKilled: 1 numKilled: 1 numKilled: 1 numKilled: 1 numKilled: 1 ...The behavior I expect is that I see "numKilled: 1" exactly once, and the child process (and any of its children) is killed after roughly 5 seconds. But I see from experiment that neither the child nor its children are getting killed. The kill(SIGTERM, $childPid) appears to do nothing.
How can I actually kill the child?
最满意答案
来自perldoc fork :
如果你没有等待你的孩子分岔,你会积累僵尸。 在某些系统上,您可以通过将$ SIG {CHLD}设置为“IGNORE”来避免这种情况。
添加$SIG{CHLD} = 'IGNORE';时,我能够获得所需的行为$SIG{CHLD} = 'IGNORE'; 到您的代码的顶部。
[ben@imac ~]$ perl test.pl numKilled: 1 [ben@imac ~]$或者,添加waitpid($childPid, 0); kill后也做了这个伎俩。
From perldoc fork:
If you fork without ever waiting on your children, you will accumulate zombies. On some systems, you can avoid this by setting $SIG{CHLD} to "IGNORE" .
I was able to get the desired behavior when adding $SIG{CHLD} = 'IGNORE'; to the top of your code.
[ben@imac ~]$ perl test.pl numKilled: 1 [ben@imac ~]$Alternatively, adding waitpid($childPid, 0); after kill did the trick as well.
更多推荐
发布评论