|
Hello,
I have a sub routine that is supposed to submit a call to an external program. It should wait for some number of seconds for a response to be returned. If no response is returned within the given number of seconds, the sub routine should kill the process and return a TIMEOUT response.
I did not write this code and I'm not really clear on how it all works but it's not doing what it's supposed to in the case of a timed out transaction. I think it is somehow spawning children of the program itself, not the external one but the one that contains the sub routine. I'm not sure though.
Can someone tell me what might be causing this code not to work properly, or suggest and alternative method of carrying out the above mentioned task?
Thanks in advance for your assistance.
sub run_transaction {
use POSIX "waitpid";
my $timeout_seconds = 93;
my $timeout = time + $timeout_seconds;
my (@args) = @_;
my $prog = "trans_server";
my $output;
my $thepid;
my $child;
$output = "";
die "Can't fork: $!" unless defined ($thepid = open(KID, "-|"));
if ($thepid) {
do {
$child = waitpid($thepid, &POSIX::WNOHANG);
} while time < $timeout && $thepid ne $child;
if($thepid ne $child) {
&kill_trans_server;
$new_timeout = time + $timeout_seconds;
do {
$new_child = waitpid($thepid, &POSIX::WNOHANG);
} while time < $new_timeout && $thepid ne $new_child;
if($thepid ne $new_child) {
$k = kill 'HUP', $thepid;
sleep 2;
$k = kill 9, $thepid;
waitpid($thepid, 0);
close KID;
return "4:TIMED OUT";
}
}
while (<KID>) {
$output .= $_;
}
close KID;
} else {
$ENV{PATH} = "/bin:/usr/bin";
exec "$prog", @args or die "can't exec $prog: $!";
}
if ((defined($@)) && $@) {
$output = "ERROR: $@";
}
return $output;
}
|
|
|
|
|
|
|
|