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

Categories

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

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

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...