0

我有一个运行下标来收集 5 行信息的 perl 脚本。目前它正在这样做:

my @info = split(/\n/,`/script/directory/$devtype.pl $ip $port`);

但是,由于我无法控制的各种原因,下标有时会挂起,在这种情况下,我只想停止下标并继续前进。什么是最好的方法

  • 获取下标的PID
  • 等待这 5 行输出,如果在设置的超时之前未收到输出,则杀死 -9 pid

我在考虑useing Forks::Super@info与下标共享,并有一个循环等待数组填满,直到超时。但是,我不确定如何在不重写下标的情况下实现这一点,由于与其他脚本的向后兼容性,我不希望这样做。

4

1 回答 1

2

以下代码使用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;
}
于 2012-12-02T19:52:19.817 回答