Hi Guys,
I'm trying to 'safely' execute a shell command passed to a function (exec_safe).
My intention is to return the output of the shell command and the exit code if the command completes.
exec_safe receives the following:
$_[0] = Command to be run. This may contain pipes, redirects, etc.
$_
1 = The timeout (seconds) for the command
$_
2 = A nice value that the command is run at.
After some googling, etc I've come up with the following (Comments included):
sub exec_safe {
my @cmd; # Return variable
eval {
local $SIG{ALRM} = sub { die "Timeout\n" };
alarm $_[1];
@cmd = `nice -n $_[2] $_[0]`;
alarm 0;
};
if($@) { # If command fails, return non-zero and msg
return ("Command timeout",1);
} else {
chomp @cmd; push(@cmd,$? >> 8);
return @cmd;
}
}
While this operates correctly in allowing the perl program to continue after the timeout, in testing it's not terminating the spawned process.
For example, if I call 'sleep 250' with a timeout of 10, the function will return after 10 seconds with
"Command Timeout",1, however PS shows that the process 'sleep 250' is still running.
Caveat: Note that because I'm looking for the returned data and exit code of the child process, exec_safe cannot return until it's finished or timed out.
From a brief googlin', it doesn't appear that fork will allow me to get all the data I need.
Any ideas?