in reply to Re^2: Detecting Dead Socket Connection
in thread Detecting Dead Socket Connection

I think what you want is to use select to see if there is anything ready to be read before calling eof. Well, I kinda lied. Using select is sorta like drilling a hole in one's head - you can do it, but you probably want another solution.

That's where IO::Select comes in. Same piercing, but much faster (to figure out) and less painful. You can assign a timeout, and then do what you want with the filehandle. As long as the socket remains open and unused, select should timeout, but if the socket is closed, select should return the status change (probably by asking "has_exception", but I haven't tested this).

Replies are listed 'Best First'.
Re^4: Detecting Dead Socket Connection
by scmason (Monk) on Mar 18, 2005 at 23:57 UTC
    Yes! You are correct sir! Drawing from c experience, I went with somethink like this:
    #Passive check for down socket my $sin = ""; vec($sin, fileno(SESSION),1 ) = 1; my $nfound = select($sin, undef, undef, .01); if ($nfound != 0){ if( eof(SESSION) == 1 ){ die "Socket is dead on passive check\n"; } }

    Here I told select to time out after .01 seconds. If the connection goes down (gracefully) then $nfound returns something greater than 0 (the disconnect packet?) but an eof on the socket then determines that socket handle SESSION is at EOF and so the program dies, or whatever.

    It is worth noting, however, that if the connection does NOT go down gracefule, like the remote network cable comes unplugged, then this does not work as expected. Select WILL return 0.

      How perl handles an ungraceful socket disconnections is largely a function of how the underlying TCP stack handles it. I don't think you'll get much, if any, better than this.