简体   繁体   English

捕获下标中的输出,超时

[英]Capturing output from a subscript, with a timeout

I have a perl script that runs a subscript to gather 5 lines of information. 我有一个运行下标的perl脚本来收集5行信息。 At present it is being done like this: 目前正在这样做:

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

However, for various reasons outside of my control, the subscript can sometimes hang, and in those cases i would like to just stop the subscript and move on. 但是,由于我控制之外的各种原因,下标有时会挂起,在这种情况下,我想停止下标并继续前进。 What would be the best approach to 什么是最好的方法

  • Get the PID of the subscript 获取下标的PID
  • Wait for those 5 lines of output, and kill -9 the pid if output isn't received before a set timeout 等待那5行输出,如果在设置超时之前没有收到输出,则kill -9 pid

I was thinking of use ing Forks::Super , share @info with the subscript, and have a loop that waits for the array to fill up, up to the timeout. 我正在考虑use Forks::Super ,与下标共享@info ,并有一个等待数组填充的循环,直到超时。 However, i'm not sure how to achieve this without rewriting the subscript, something i'd prefer not to because of backwards-compatibility with other scripts. 但是,我不知道如何在不重写下标的情况下实现这一点,因为与其他脚本的向后兼容性,我不愿意这样做。

The following code uses IPC::Run to fetch 5 lines to @info with a timeout of 30 seconds and assure the child process is dead: 以下代码使用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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM