#!/usr/bin/perl
#
# Potential fix for signal handling in LWP by:
#
#  Kyle Burton (krbuton@cpan.org)
#  Ben Kennedy (bkennedy@hmsonline.com)
#
# When a process receives a signal (ALRM, CHLD, etc) any 
#  blocking select() calls will immediately return -1 and 
#  set errno to 4 (EINTR).  The code currently interprets
#  this interruption as a socket timeout, which causes the
#  entire request to fail.  The fix looks at the return
#  value of select(), and re-tries the request until the
#  timeout is reached (or forever).
#
# Note: we have tested this solution on Linux, and there
#  doesn't seem to be an issue with Win32
#

use strict;
use warnings;

use LWP::Protocol::http;

package LWP::Protocol::http::SocketMethods;
  
sub can_read {
  my($self, $timeout) = @_;

  my $to = ${*$self}{io_socket_timeout};
  my $start = time();
  
  while(1) {
    last if $to and ((time() - $start) > $to);

    my $fbits = '';
    vec($fbits, fileno($self), 1) = 1;
    my $nfound = select($fbits, undef, undef, $timeout);
    die "select failed: $!" unless defined $nfound;
    
    if ($nfound > 0) {
      return(1);
    }
    
    # EINTR signal - select was interrupted by a signal
    #
    if ($! == 4) {
      print STDERR "_ Retrying select due to EINTR\n";
      next;
    }
    
    die "select failed: $!";
  }
  
  die "select failed - timeout reached: $!";
}


package main;

use LWP::UserAgent;

my $acount = 0;

$SIG{ALRM} = sub { print "Got sig\n"; $acount++; alarm(1) };
alarm(1);

my $ua = new LWP::UserAgent;
my $req = new HTTP::Request('GET', "http://www.microsoft.com/");

my $count = 0;

while(1) {
  $count++ % 10 or print "* At $count ($acount)\n";
  my $resp = $ua->request($req);
  unless($resp->is_success) {
    die $resp->error_as_HTML;
  }
}

