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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Displaying an arrayList in a listView using the default adapter is rarely the best solution. To get full control of your display data, and to be able to refresh it after editing, requires the use of a custom adapter.
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 …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

760 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

19 Experts available now in Live!

Get 1:1 Help Now