xarex has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks
i have a forking server that is accepting connections, writing a log and then closing
The proble i have is that sometimes, the client does not send data
and this is keeping the connection open,
is there some way that i can close the connection say after 2 min if there is no data sent?
below is a snippet of what i currently have
while(my $connection = $server->accept){ my $name = $connection->peerhost; my $port = $connection->peerport; if (my $pid = fork){ close $connection; next; # on to the next connection }else{ # child process - handle connection print $connection "You're connected to the server!\n"; while (<$connection>){ use HTTP::Date; my ($date, $time) = split(" ", HTTP::Date::time2iso()); my ($hour, $min) = split(":", $time); open (my $log, '+>>',"../../home/freetrac/public_html/logs/$po +rt $date.txt") || die "Couldn't open log.txt: $!"; print $log $_; close $log; exit(0); } $connection->shutdown(SHUT_RDWR); exit; } }

Any help would be great
Thanks
K-

Replies are listed 'Best First'.
Re: socket time out
by oha (Friar) on Nov 09, 2007 at 15:27 UTC
    you could try using alarm in an eval block (untested):
    eval { local $SIG{'ALRM'} = sub { die "Timed out" }; alarm($timeout); while(<$conn>) { .... alarm($timeout); } alarm(0); } if ($@ =~ /Timed out/) { print STDOUT "Timed Out.\r\n"; }
    Oha
      being new to perl i tried that exactly as you said
      but its giving complitaion errors,
      could you please try to be a little more specific?
      Thanks
      K-
        It's just missing a ; in the example at the end of the eval closing brace:
        eval {
            local $SIG{'ALRM'} = sub { die "Timed out" };
            alarm($timeout);
            while(<$conn>) {
               ....
               alarm($timeout);
            }
            alarm(0);
        };
        if ($@ =~ /Timed out/) {
            print STDOUT "Timed Out.\r\n";
        }
        
Re: socket time out
by weismat (Friar) on Nov 09, 2007 at 17:09 UTC
    Use IO::Select.
    my $select=new IO::Select(); $select->add($connection); if ($select->can_read($timeout) { #handle timely answer } else { #timeout }