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

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

问题描述

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

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
" 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: $!
";
                while(<CMD>) {
                        $response .= $_;
                }
                close(CMD) || die "Couldn't close execution of @command: $!
";
                $response;
        };
        alarm(0);
        if ($@) {
                warn "@cmd failure: $@
";
        }
        return $return;
}

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

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