4th Floor, 4 Tabernacle Street London EC2A 4LU

Perl – Execute Command With Timeout

[perl]

my $command_to_check = “$SSH_CON $host $SSH_CMD”;
if (! execute_command($command_to_check)) {
next;
}

sub execute_command($)
{
### Executes a command with timeout
### Returns 0 if fails
### Returns 1 on success

my $command=shift;
my $timeout=30;

eval {
local $SIG{ALRM} = sub{die;};
my($oalarm) = alarm($timeout);
$result=`$command 2>&1`;
if ($? ne 0) {
writeLog(“Error: Command execution failed ($!) – running – $command”);
$error_msg.=”Error: Command execution failed ($!) – running – $command\n\n”;
$returnValue=2;
} else {
writeLog(“Success: $command”);
}
alarm($oalarm);
};

## Result is not defined after timeout duration
## Exit with 0;
if ( ! defined($result) )
{
writeLog(“Error: $command timed-out and failed”);
return 0;
} else {
## Success
return 1;
}
}

[/perl]