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 .开发者_StackOverflow If the nothing is read . It has to return in specified timeout. what is the way...?
Thanks
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.
perldoc -f alarm
If you want to use
alarm
to time out a system call you need to use aneval
/die
pair. You can't rely on the alarm causing the system call to fail with$!
set toEINTR
because Perl sets up signal handlers to restart system calls on some systems. Usingeval
/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.
精彩评论