Created
May 16, 2016 06:47
-
-
Save fujiwara/32442e40e6bdd9c7d18ba602a6bdba66 to your computer and use it in GitHub Desktop.
Hard timeout for LWP::UserAgent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use 5.12.1; | |
use POSIX ":sys_wait_h"; | |
use Log::Minimal; | |
use LWP::UserAgent; | |
use Time::HiRes qw/ sleep time /; | |
use HTTP::Request::Common; | |
my ($url, $output, $timeout) = @ARGV; | |
if (-e $output) { | |
unlink $output or die $!; | |
} | |
my $pid; | |
if ($pid = fork) { | |
# parent | |
my $start = time; | |
while (1) { | |
my $kid = waitpid($pid, WNOHANG); | |
if ($kid) { | |
infof "%d is exited", $kid; | |
last; | |
} | |
if (time - $start > $timeout) { | |
warnf "timed out. kill -KILL %d", $pid; | |
kill 'KILL', $pid; | |
} | |
sleep 0.1; | |
} | |
} else { | |
# child | |
my $ua = LWP::UserAgent->new; | |
my $req = GET $url; | |
infof "starting %s", $req->as_string; | |
$ua->request( $req => $output ); | |
infof "child done"; | |
exit; | |
} | |
infof "%s size %d bytes", $output, ( -s $output ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment