Perl的fork和kill

编程入门 行业动态 更新时间:2024-10-25 09:24:57
Perl的fork和kill - kill(0,$ pid)总是返回1,并且不能杀死子进程(Perl fork and kill - kill(0, $pid) always returns 1, and can't kill the child)

我在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.

更多推荐

本文发布于:2023-08-02 23:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382466.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Perl   fork   kill

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!