[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] SAMPLE: Timed execute of external command with timeout.



I thought I would thrown this out to the world incase anyone needs this in the future.  Might help those of us who "Google" though new challenges... :-)

Months ago I wrote a script that ran an external program and parsed the output for errors.  Unfortunatly, one of the errors that I did not anticipate was the external program hanging forever.  The usual
     $result = `/path/to/cmd`;
hung and never returned -- thus the script never completed.

I ended up writing this subroutine to call the command with a timeout window defined.
example:
     ($TimeoutStatus, $CmdResult) = timedexec(90,"/path/to/cmd");
This will call the program "command" and wait 90 seconds for it to complete.  The returned value in $TimeoutStatus will be 0(success) or 1(failure).  The value in $CmdResult will be the text output returned by the command (to stdout).

Dan

sub timedexec {
# timedexec : This subroutine will run a command within a specified time
#             window (in seconds).
# RETURNS : Returns an array of two elements:
#  Success : first element is 0
#            second element is the text returned by the command.
#  Failure : first element is 1
#            second element is empty.
#
        my $alarm=shift;
        my $CMD=shift;
        my $result = "";
        my $status = 0;

        eval {
                local $SIG{ALRM} = sub { die "alarm\n" }; # \n required
                alarm $alarm;
                $result = `$CMD`;
                alarm 0;
        };
        die if $@ && $@ ne "alarm\n";       # propagate errors
        if ($@) {
                # timed out : return the error code.
                $status=1;
                $result="";
        }
        else {
                # didn't time out : return a success code.
                $status=0;
        }

        return ($status, $result);
}



- - - -
"Wait for that wisest of all counselors, time." -- Pericles
"I do not fear computers, I fear the lack of them." -- Isaac Asimov
"Soon we will be able to harness the rotational energy from Orwell's grave to solve all world energy problems." -- /. user GigsVT (208848)
GPG fingerprint:6FFD DB94 7B96 0FD8 EADF 2EE0 B2B0 CC47 4FDE 9B68