How to catch timeout exception with IPC::Run on Windows 10?

核能气质少年 提交于 2021-01-27 19:55:56

问题


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});
}

The above program dies after 3 seconds with:

Terminating on signal SIGBREAK(21)

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

See also this issue.


回答1:


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});
} 

Output:

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


来源:https://stackoverflow.com/questions/65894141/how-to-catch-timeout-exception-with-ipcrun-on-windows-10

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!