Read from TCP socket with broken connection.

Sergei Organov osv at javad.ru
Wed Apr 11 06:59:21 UTC 2001


Eric Norum <eric.norum at usask.ca> writes:
> Sergei Organov wrote:
> > 
> > When a socket was connected but remote host has closed connection, how
> > subsequent read/write operations should behave? My observation is that read()
> > returns 0 and doesn't set 'errno'. Is it correct behavior?
> 
> Yes.
> 
> > 
> > If yes, then how do I distinguish between reading from such a socket and
> > reading from connected socked that results in time-out with zero bytes
> > received? Or, alternatively, how to detect that remote host has closed
> > connection?
> 
> If you've used setsockopt to set a receive timeout and the sender
> doesn't transmit within that time limit the read will return an error
> (-1) with errno set.  Otherwise a read will block forever if the remote
> machine terminates without closing down the socket (unless you've turned
> on KEEPALIVE messages).

Thanks, Eric. I'll give it a try.

For whatever reason I thought the behavior should be opposite: return -1 if
connection is broken, and 0 on time-out. Apparently it was my mistake. :-( I
don't have BSD manuals handy and glibc manual doesn't describe timeouts on
sockets at all :-(

Thank you again.

BR,
Sergei.


> -- 
> Eric Norum                                 eric.norum at usask.ca
> Department of Electrical Engineering       Phone: (306) 966-5394
> University of Saskatchewan                 FAX:   (306) 966-5407
> Saskatoon, Canada.




More information about the users mailing list