Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, make script timeout after x number of seconds?

Tags:

timeout

perl

I have been searching on this but it is surprisingly hard to come by a straight answer to this (as php has a lot more info on this topic it seems).. I need to make my perl script die after a specified number of seconds because, as it is now, they are running too long and clogging up my system, how can I make it so the entire script just dies after a specified number of seconds?

I know about external solutions to kill the script but I would like to do it from within the perl script itself.

Thanks

like image 582
Rick Avatar asked Dec 09 '22 14:12

Rick


2 Answers

perldoc -f alarm:

[sinan@kas ~]$ cat t.pl
#!/usr/bin/perl

use strict; use warnings;

use Try::Tiny;

try {
        local $SIG{ALRM} = sub { die "alarm\n" };
        alarm 5;
        main();
        alarm 0;
}
catch {
        die $_ unless $_ eq "alarm\n";
        print "timed out\n";
};

print "done\n";

sub main {
        sleep 20;
}

Output:

[sinan@kas ~]$ time perl t.pl
timed out
done

real    0m5.029s
user    0m0.027s
sys     0m0.000s
like image 122
Sinan Ünür Avatar answered Dec 28 '22 22:12

Sinan Ünür


See alarm in perldoc:

eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = sysread SOCKET, $buffer, $size;
    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # propagate unexpected errors
    # timed out
}
else {
    # didn't
}
like image 24
Pedro Silva Avatar answered Dec 29 '22 00:12

Pedro Silva