如何在Perl中异步运行系统命令? [英] How can I run a system command in Perl asynchronously?

查看:96
本文介绍了如何在Perl中异步运行系统命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个Perl脚本,该脚本在系统上运行一个外部命令,收集输出,并根据返回的内容执行一些操作.现在,这是我的运行方式(其中$ cmd是使用命令setup的字符串):

I currently have a Perl script that runs an external command on the system, gathers the output, and performs some action based on what was returned. Right now, here is how I run this (where $cmd is a string with the command setup):

@output = `$cmd`;

我想更改此设置,以便如果命令挂起并且经过这么长的时间后未返回任何值,那么我将终止该命令.我将如何异步运行它?

I'd like to change this so if the command hangs and does not return a value after so much time then I kill the command. How would I go about running this asynchronously?

推荐答案

如果您真的只需要在给定的系统调用上设置超时,则该问题比异步编程要简单得多.

If you really just need to put a timeout on a given system call that is a much simpler problem than asynchronous programming.

您需要的只是eval()块中的alarm().

All you need is alarm() inside of an eval() block.

这是一个示例代码块,可将其放入子例程中,您可以将其放入代码中.该示例调用sleep,因此输出并不令人兴奋,但确实向您显示了您感兴趣的超时功能. 运行它的输出是:

Here is a sample code block that puts these into a subroutine that you could drop into your code. The example calls sleep so isn't exciting for output, but does show you the timeout functionality you were interested in. Output of running it is:

/bin/sleep 2失败:超时时间为 ./超时行15.

/bin/sleep 2 failure: timeout at ./time-out line 15.

$ cat time-out
#!/usr/bin/perl

use warnings;
use strict;
my $timeout = 1;
my @cmd = qw(/bin/sleep 2);
my $response = timeout_command($timeout, @cmd);
print "$response\n" if (defined $response);

sub timeout_command {
        my $timeout = (shift);
        my @command = @_;
        undef $@;
        my $return  = eval {
                local($SIG{ALRM}) = sub {die "timeout";};
                alarm($timeout);
                my $response;
                open(CMD, '-|', @command) || die "couldn't run @command: $!\n";
                while(<CMD>) {
                        $response .= $_;
                }
                close(CMD) || die "Couldn't close execution of @command: $!\n";
                $response;
        };
        alarm(0);
        if ($@) {
                warn "@cmd failure: $@\n";
        }
        return $return;
}

这篇关于如何在Perl中异步运行系统命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆