【发布时间】:2013-02-21 21:10:01
【问题描述】:
我在 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) 似乎什么也没做。
我怎样才能真正杀死孩子?
【问题讨论】:
-
您是从某个地方导入
SIGTERM常量吗?我敢打赌它的评估结果为 0。 -
你在使用
use warnings; use strict;吗?为什么不呢? -
嘿伙计们,所以我发现我看到的问题实际上有点不同 - kill 正在杀死子进程而不是它的任何子进程。我不想只编辑整个问题,我应该开始一个新问题吗?
-
有点题外话,但在对您的子进程句柄进行任何操作之前,请考虑检查
if ( defined( $childPid ) )。forkreturnsundef如果创建进程失败。
标签: perl