Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...