AMcNall
AMcNall

Reputation: 529

Perl - If system command fails or runs for too long how can I stop it or run another system call?

I have a perl script that executes many other scripts at certain times.

Once in a while these other script may hang permanently or outright fail, but there is no current way to tell if these other scripts do so.

How can I implement a way to check if a script either runs for too long (so the user can take action) or outright fails. The plan being an email can be sent to the appropriate user notifying them.

Example of the system call below:

elsif ($job_type eq 'script') { 
    system("perl $job_dir/$job_args > $work_dir/$job_name.out 2> work_dir/$job_name.err");
}

Upvotes: 0

Views: 1042

Answers (2)

user3967089
user3967089

Reputation:

You may want to have a look at the CPAN module IPC::Run. It packages up a lot of the fiddly details for you. Its documentation is pretty bad, but once you get through enough of it to understand how to do things it's very convenient.

Upvotes: 0

Miller
Miller

Reputation: 35208

Use an alarm:

eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm 120;   # 2 Minute timeout

    system("perl $job_dir/$job_args > $work_dir/$job_name.out 2> work_dir/$job_name.err");

    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # Propagate unexpected errors

    # Timed out - Send out email to user
    ...

} else {
    # Successfully ran command.  Any cleanup here.
    ...
}

Upvotes: 1

Related Questions