如何在 Windows 10 上使用 IPC::Run 捕获超时异常? [英] How to catch timeout exception with IPC::Run on Windows 10?

查看:25
本文介绍了如何在 Windows 10 上使用 IPC::Run 捕获超时异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Windows 10 上使用 IPC::Run 捕获超时异常(使用 Strawberry Perl 版本 5.30.1):

I am trying to catch a timeout exception with IPC::Run on Windows 10 (using Strawberry Perl version 5.30.1):

use strict;
use warnings;
use feature qw(say);
use Data::Dumper;
use IPC::Run qw(run timeout);

my $timeout = 3;
my $cmd = ['perl', '-E', "sleep 5; say 'stdout_text'; say STDERR 'stderr_text'"];
my $in;
my $out;
my $err;
my $result;
eval {
    $result = run $cmd, \$in, \$out, \$err, timeout($timeout );
};
if ( $@ ) {
    say "Timed out: $@";
}
else {
    print Dumper({  out => $out, err => $err});
}

上述程序在 3 秒后终止:

The above program dies after 3 seconds with:

Terminating on signal SIGBREAK(21)

如何在 Perl 脚本中捕获超时异常?

How can I catch the timeout exception in the Perl script?

另见这个问题.

推荐答案

感谢 @zdim!您需要为 BREAK 信号安装一个信号处理程序.以下工作:

Thanks to @zdim! You need to install a signal handler for the BREAK signal. The following works:

use strict;
use warnings;
use feature qw(say);
use Data::Dumper;
use IPC::Run qw(run timeout);

my $timeout = 3;
my $cmd = ['perl', '-E', "sleep 4; say 'stdout_text'; say STDERR 'stderr_text'"];
my $in;
my $out;
my $err;
my $result;
{
    local $SIG{BREAK} = sub { die "Got timeout signal" };
    eval {
        $result = run $cmd, \$in, \$out, \$err, timeout($timeout );
    };
}
if ( $@ ) {
    say "Timed out: $@";
}
else {
    print Dumper({  out => $out, err => $err});
} 

输出:

> perl p.pl
Timed out: Got timeout signal at p.pl line 14.

这篇关于如何在 Windows 10 上使用 IPC::Run 捕获超时异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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