用fork创建杀死子进程

时间:2014-08-27 13:24:46

标签: perl fork

以下将输出:

Start of script
PID=29688
Start of script
PID=0
Running child process 1
Done with child process
PID=29689
Start of script
PID=0
Running child process 1
Done with child process

它按预期工作,但是我想杀掉之前的子PID。

如何在没有杀死MAIN的情况下杀死孩子的PID?

谢谢!

my $bla = 1;

while (1) {

print "Start of script\n";
run_sleep();

}

sub run_sleep {

    sleep(3);
    my $pid = fork;

    return if $pid;     # in the parent process
    print("PID=" . $pid . "\n");
    print "Running child process " . $bla++ . "\n";
    exit(0);  # end child process

}

1 个答案:

答案 0 :(得分:2)

当你分叉一个孩子,然后无法等待它时,它会在它退出时成为一个已经失效的过程(Unix术语中的僵尸)。您会注意到它的父进程ID变为1,并且在操作系统重新启动之前它不会消失。

所以传统的forking伪代码看起来像这样:

if ($pid = fork()) {
   # pid is non-zero, this is the parent
   waitpid($pid)   # tell OS that we care about the child

   do other parental stuff
}
else {
   # pid is 0 so this is the child process
   do_childish_things()
}

你的代码没有这样做,所以你可能会变得僵尸,然后因为你无法摆脱它们而感到沮丧。

相关问题