【发布时间】:2015-10-24 18:04:02
【问题描述】:
我正在用 PERL 编写一个仿真存根来测试另一个程序。下面,代码运行一个循环来检查命令(initialize、exit、start_trace、stop_trace)。当读取“start_trace”命令时,它会派生一个每秒只吐出数字的进程。我想用“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
%
但他们都退出了!为什么?
【问题讨论】: