我正在使用PERL编写仿真桩来测试另一个程序。下面的代码运行了一个循环,检查命令(初始化,退出,开始跟踪,停止跟踪)。当读取“start_trace”命令时,它会fork一个进程,每秒钟输出一些数字。我想使用“stop_trace”来杀死子进程,但它也会杀死父进程。我错过了什么?
use warnings;
use strict;
my $pid = undef;
$| = 1;
$SIG{TERM} = sub {
if ($pid == 0) {
print "Parent, not terminating\n";
} else {
print "Child ($pid) terminating\n";
exit(1);
}
};
print "entering loop\n";
while (1) {
while (<>) {
my ($command, @args) = split();
if ($command eq "exit") {
exit 1;
}
elsif ($command eq "initialize") {
print "s: ok\n";
}
elsif ($command eq "start_trace") {
if (defined $pid) {
print "child already running\n";
} else {
$pid = fork();
if ($pid == -1) {
print "failed to fork\n";
exit 1;
}
elsif ($pid == 0) {
print "Parent\n";
}
else {
my $timestamp = 0;
while (1) {
for (my $i = 0; $i < 12; ++$i) {
printf "%.3f %.0f %.2f %.1f\n",
++$timestamp,
0,
0,
100 * rand()
;
}
sleep(1);
}
}
}
}
elsif ($command eq "stop_trace") {
kill "TERM", $pid;
#waitpid($pid, 0);
$pid = undef;
}
else {
printf "s: unknown command $command\n";
}
}
}
输出结果(标准输入和标准输出混合在一起,但我正在输入“stop_trace”)
stop85.000 0 0.00 66.6
86.000 0 0.00 43.3
87.000 0 0.00 82.3
88.000 0 0.00 62.8
89.000 0 0.00 43.5
90.000 0 0.00 50.0
91.000 0 0.00 8.8
92.000 0 0.00 89.3
93.000 0 0.00 61.4
94.000 0 0.00 92.4
95.000 0 0.00 46.6
96.000 0 0.00 53.9
_trace
Child (26644) terminating
Parent, not terminating
%
但他们都退出了!为什么?