我在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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
aschirma@graphics9-lnx:~$ perl perl-fork-test.pl
numKilled: 1
numKilled: 1
numKilled: 1
numKilled: 1
numKilled: 1
...
Run Code Online (Sandbox Code Playgroud)
我期望的行为是我看到"numKilled:1"恰好一次,并且子进程(及其任何子进程)在大约5秒后被杀死.但我从实验中看到,孩子和孩子都没有被杀.该kill(SIGTERM, $childPid)显得无能为力.
我怎么能真的杀了孩子?
应该是这样的.这不遵循最佳做法,但它应该可以帮助您解决问题...
#!/usr/bin/perl
use warnings;
use strict;
use POSIX qw(:sys_wait_h);
my $timeOut = 5;
$SIG{ALRM} = \&timeout;
$SIG{CHLD} = 'IGNORE',
alarm($timeOut);
my $childPid = fork();
if ($childPid) {
while(1) {
print "[$$]: parent...\n";
sleep(2);
}
}else {
# I am the child - do something that blocks forever
while(1){
print "[$$]: child...\n";
sleep(2);
}
exit;
}
sub timeout {
print "killing $childPid\n";
print "###\n" . `ps -ef | grep -v grep | grep perl` . "###\n";
if ( ! (waitpid($childPid, WNOHANG)) ) {
print "killing $childPid...\n";
kill 9, $childPid;
die "[$$]: exiting\n";
}
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
$ forktest.pl
[24118]: parent...
[24119]: child...
[24118]: parent...
[24119]: child...
[24118]: parent...
[24119]: child...
killing 24119
###
cblack 24118 12548 0 14:12 pts/8 00:00:00 /usr/bin/perl ./forktest.pl
cblack 24119 24118 0 14:12 pts/8 00:00:00 /usr/bin/perl ./forktest.pl
###
killing 24119...
[24118]: exiting
Run Code Online (Sandbox Code Playgroud)