If a command might go haywire and hang your script, a good defense is to use alarm
and a SIGALRM
handler to make the command time out.
sub system_with_timeout {
my ($timeout, @command) = @_;
local $SIG{ALRM} = sub { die "Timeout\n" };
my $result;
if ($timeout > 0) { alarm $timeout; }
eval {
$result = system(@command);
};
if ($@ =~ /Timeout/) {
warn "@command timed out.\n";
return -1;
}
return $result;
}
Check the return values to make sure your command was successful or whether it timed out.
my $z = system_with_timeout(30, "systemsetup -setusingnetworktime off");
if ($z == 0) {
# success ...
} elsif ($z == -1) {
# timed out ... try it again ?
} else {
# failed for some other reason ...
}
mobrule
2010-08-26 20:49:51