以下代码使用IPC::Run以 30 秒的超时获取 5 行@info
并确保子进程已死:
#!/usr/bin/env perl
use strict;
use warnings qw(all);
use IPC::Run qw(start timeout new_chunker input_avail);
my @info;
my $h;
# trap timeout exception
eval {
$h = start
# beware of injection here!
# also, $^X holds the name of your actual Perl interpreter
[$^X, "/script/directory/$devtype.pl", $ip, $port],
# read STDOUT line-by line
'>', new_chunker,
# handle each line
sub {
my ($in, $out) = @_;
if (input_avail) {
if (5 > @info) {
chomp $in;
push @info, $in;
return 1;
} else {
return 0;
}
}
},
timeout(30);
# is it dead yet?
$h->finish;
};
# make sure it is dead
if ($@) {
warn "exception: $@";
$h->kill_kill;
}