views:

147

answers:

1

I know that read() is a blocking call unless I make the socket non-blocking. So I expect read() call which requests 4K of data should return a positive value ( no of bytes read) or -1 on error ( possible connection reset by client etc). My question is: Can read() return '0' on any occasion?

I am handling the read() this way:

   if ((readval = read(acceptfd, buf, sizeof(buf) - 1)) < 0)
    {

    }
    else
    {
       buf[readval] = 0;
       //Do some thing with data  
    }

This code bombs if read() return zero and I know how to fix it. But is it possible for read() to return zero?

+3  A: 

When a TCP connection is closed on one side read() on the other side returns 0 byte.

skwllsp
Shouldn't the read return -1 with errno set to ECONNRESET? It is actually an error condition, if other side has closed the connection. Should we consider return of zero also as error condition?
kumar
+1 read() returns zero when the connection is closed.
Richard Pennington
@kumar: returning zero allows you to determine that an orderly shut down occurred, as opposed to a real error.
Richard Pennington
@Richard, Thanks. So I should consider zero as error condition and close the connected socket. Right?
kumar
Yes, you should close the connected socket. However it is not an error.
skwllsp