How to time out system call in Perl?

Posted on 2011-03-22
Last Modified: 2012-05-11
How can I time out if system call hangs for more than let's say 20 seconds?

system(java -jar  ===> time out this if it hangs more than 20 seconds

Open in new window

Question by:Tolgar
  • 2

Expert Comment

ID: 35194654
You can do this with by running the system() call in a thread, polling $thr->is_joinable() from another thread after the desired delay, and then taking the necessary action to kill the spawned process if it returns false.

Alternatively, here's a good single-threaded example I found with google that uses SIGALRM:

use Error qw(:try);

$SIG{ALRM} = sub {
    my $sig_name = shift;
    die "Timeout by signal [$sig_name]\n";

# example
my $command = "vmstat 1 1000000";
my $output = backtick( 
                 command => $command, 
                 timeout => 60, 
                 verbose => 0 

sub backtick {

    my %arg = (
        command => undef,
        timeout => 900,
        verbose => 1,

    my @output;

    defined( my $pid = open( KID, "-|" ) )
        or die "Can't fork: $!\n";

    if ($pid) {

        # parent

        # print "parent: child pid [$pid]\n" if $arg{verbose};

        try {
            alarm( $arg{timeout} );
            while (<KID>) {
                push @output, $_;

        catch Error with {
            my $err = shift;
            print $err->{-text} . "\n";

            print "Killing child process [$pid] ...\n" if $arg{verbose};
            kill -9, $pid;
            print "Killed\n" if $arg{verbose};

        finally {};
    else {

        # child

        # set the child process to be a group leader, so that
        # kill -9 will kill it and all its descendents
        setpgrp( 0, 0 );

        # print "child: pid [$pid]\n" if $arg{verbose};
        exec $arg{command};

    wantarray ? @output : join( "\n", @output );

Open in new window


Author Comment

ID: 35194762
Sorry, but I didn't fully understood the code you sent.

Is there a more straightforward way of doing it?

LVL 28

Accepted Solution

FishMonger earned 500 total points
ID: 35194851
D:\perl>perldoc -q timeout
Found in C:\Perl\lib\pods\perlfaq8.pod
  How do I timeout a slow event?
    Use the "alarm()" function, probably in conjunction with a signal
    handler, as documented in "Signals" in perlipc and the section on
    "Signals" in the Camel. You may instead use the more flexible
    "Sys::AlarmCall" module available from CPAN.

    The "alarm()" function is not implemented on all versions of Windows.
    Check the documentation for your specific version of Perl.


D:\perl>perldoc -f alarm
    alarm SECONDS
    alarm   Arranges to have a SIGALRM delivered to this process after the
            specified number of wallclock seconds has elapsed. If SECONDS is
            not specified, the value stored in $_ is used. (On some
            machines, unfortunately, the elapsed time may be up to one
            second less or more than you specified because of how seconds
            are counted, and process scheduling may delay the delivery of
            the signal even further.)

            Only one timer may be counting at once. Each call disables the
            previous timer, and an argument of 0 may be supplied to cancel
            the previous timer without starting a new one. The returned
            value is the amount of time remaining on the previous timer.

            For delays of finer granularity than one second, the Time::HiRes
            module (from CPAN, and starting from Perl 5.8 part of the
            standard distribution) provides ualarm(). You may also use
            Perl's four-argument version of select() leaving the first three
            arguments undefined, or you might be able to use the "syscall"
            interface to access setitimer(2) if your system supports it. See
            perlfaq8 for details.

            It is usually a mistake to intermix "alarm" and "sleep" calls,
            because "sleep" may be internally implemented on your system
            with "alarm".

            If you want to use "alarm" to time out a system call you need to
            use an "eval"/"die" pair. You can't rely on the alarm causing
            the system call to fail with $! set to "EINTR" because Perl sets
            up signal handlers to restart system calls on some systems.
            Using "eval"/"die" always works, modulo the caveats given in
            "Signals" in perlipc.

                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

            For more information see perlipc.


Sys::AlarmCall - A package to handle the logic in timing out calls with alarm() and an ALRM handler, allowing nested calls as well.

Time::Out - Easily timeout long running operations

Author Comment

ID: 35195075
Thank you for your replies!!

So is this code correct? I am curious about line 9 ($?) After putting system call into timeout, does it still have the same meaning which is if system call returns -1 then send some emails. sendEmail is a sub function in my code which I didn't add to this email.

my $nb_sec = 60;
timeout $nb_secs => sub {
        system("java -jar");
  } ;
  if ($@){
    # operation timed-out. Send e-mail to help
    sendEmail('', '', 'Timed out', "System call interrupted due to time out");
        if ($? == -1) {
            sendEmail('', '', 'Logging Failed', "failed to execute: $!\n");
        } elsif ($? & 127) {
            printf "Child died with signal %d, %s coredump\n",
              ($? & 127),  ($? & 128) ? 'with' : 'without';
            my $signal = ($? & 127);
            my $woCoredump = ($? & 128) ? 'with' : 'without';
            sendEmail('', '', 'Logging Failed', "Child died with signal $signal, $woCodedump coredump\n");

Open in new window


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Checking the Alert Log in AWS RDS Oracle can be a pain through their user interface.  I made a script to download the Alert Log, look for errors, and email me the trace files.  In this article I'll describe what I did and share my script.
Computer science students often experience many of the same frustrations when going through their engineering courses. This article presents seven tips I found useful when completing a bachelors and masters degree in computing which I believe may he…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now