in reply to Checking if a non-blocking socket is active

I suppose that HERE I should check for some disconnect error,

Disconnection is not an error. A premature/unexpected disconnection might leave the program with partial or invalid data, but sysread doesn't care about that. It's up to the program to detect and handle that situation.

Disconnection is signaled as EOF would be for a file: Read from the socket and check if sysread returned zero (as opposed to undef). This applies to both blocking and non-blocking sockets.

For example,

use Errno qw( EAGAIN EINTR ); my $rv = sysread($sock, $buf, $BLKSIZ, length($buf)); if (!defined($rv)) { if ($! == EAGAIN) { # Only reached you are using a non-blocking socket. # No data available at the moment. Try again later. } elsif ($! == EINTR) { # Only reached if you have a signal handler. # Interrupted by signal. Try again. } else { # Error! } } elsif (!$rv) { # EOF. Socket was closed else { # Data was read }

For blocking sockets, you can check whether sysread will block or not using IO::Select. For a closed socket, it will indicate the socket is readable.

Update: I originally understood "blocking" when you said "non-blocking". I adjusted my post to compensate.

Replies are listed 'Best First'.
Re^2: Checking if a non-blocking socket is active
by bucz (Novice) on Oct 11, 2009 at 19:49 UTC

    Works like a charm! Thank you oh mighty monks!

Re^2: Checking if a non-blocking socket is active
by desemondo (Hermit) on Jul 03, 2012 at 12:19 UTC

    Thankyou very much for this code snipit ikegami! its been very helpful.

    Unfortunately, on my system I'm finding that when sysread attempts to read more data than is available at that point in time, its setting $! to A non-blocking socket operation could not be completed immediately.. As such, the program flow falls into the first else block in your code, which is intended for "real" errors.

    I went searching for the list of available Errno codes, and found the errno.h header file for my distribution. Its contents are in the readmore.

    Questions:How should I handle this situation? I'm not sure which Errno (if any) correspond to this scenario.

    Is this where IO::Select comes in?

    (If relevent, my system is Win2k8 64bit, strawberry perl 5.14.2)