Pavunkumar
Pavunkumar

Reputation: 5335

Perl : Set read timeout in client socket

I have created tcp client socket , after creating socket the connection got established with server . Then I am reading the content from server . In this case. I need to wait only for 10 seconds in read . If the nothing is read . It has to return in specified timeout. what is the way...?

Thanks

Upvotes: 1

Views: 4015

Answers (2)

ysth
ysth

Reputation: 98398

Assuming you are using the standard IO::Socket module (though there are older ways), you call the timeout method to set your timeout to 10 before reading.

Upvotes: 3

ephemient
ephemient

Reputation: 204768

perldoc -f alarm

If you want to use alarm to time out a system call you need to use an eval/die pair. You can't rely on the alarm causing the system call to fail with $! set to EINTR because Perl sets up signal handlers to restart system calls on some systems. Using eval/die always works, modulo the caveats given in Signals in perlipc.

eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = sysread SOCKET, $buffer, $size;
    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # propagate unexpected errors
    # timed out
}
else {
    # didn't
}

For more information see perlipc.

Upvotes: 1

Related Questions