开发者

Is eval/alarm is executing?

I'm writing a quick script to test the failures and interpreted traffic of a load balancer. I want it to keep trying to make connections after it can't connect to one host or another. My current script doesn't look like it's executing the eval block in the mkcnct sub, and I can't figure out why. Can anyone spot what I'm doing wrong?

#!/usr/bin/perl

use strict;
use Net::HTTP;
use Getopt::Std;

my %opts;

getopts('ht:',\%opts);

my @hostlist ("www.foo.com","www1.foo.com","www2.foo.com");

my $timeout;

if ($opts{t} =~ /\d+/) {
 $timeout = $opts{t} + time();开发者_C百科
} else {
 $timeout = 3600 + time();
}

while ($timeout < time()) {
 foreach my $host (@hostlist) {
  my $cnct = mkcnct($host);
  if ($cnct) { mkreq($cnct) };
 }
}

sub mkreq {
 my $cnct = shift;
 my $time = gettime();
 my $out;
 $cnct->write_request(GET => "/index.html");
 ($out->{code},$out->{message},%{$out->{headers}}) = $cnct->read_response_headers;
 printf "%s\t%s - Size %d\tLast modified %s\n", $time, $out->{message}, $out->{headers}{'Content-Length'}, $out->{headers}{'Last-Modified'};
 $out = "";
 $cnct->write_request(GET => "/pki/ca.crl");
 ($out->{code},$out->{message},%{$out->{headers}}) = $cnct->read_response_headers;
 printf "%s\t%s - Size %d\tLast modified %s\n", $time, $out->{message}, $out->{headers}{'Content-Length'}, $out->{headers}{'Last-Modified'};
}

sub mkcnct {
 my $host = shift;
 my $time = gettime();
 my $cnct;
 eval{
  local $SIG{ALRM} = sub { print "$time\tCannot connect to $host\n"};
  alarm(2);
  $cnct = Net::HTTP->new(Host => $host);
  alarm(0);
 };
 alarm(0);
 return($cnct);
}

sub gettime {
 my @time = localtime(time);
 my $out;
 $out = sprintf "%d\/%d\/%d %d:%d", ($time[4] + 1), $time[3], ($time[5] % 100 ), $time[2], $time[1];
 return($out);
}


Try replacing return($cnct); with return $cnct; in mkcnct. You might want to revue the docs on returning scalars and lists

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜