37

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?

fant0me
  • 201
  • 1
  • 3
  • 15
kumar
  • 2,696
  • 3
  • 26
  • 34

1 Answers1

64

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

  • 3
    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 Mar 10 '10 at 12:59
  • 1
    @kumar: returning zero allows you to determine that an orderly shut down occurred, as opposed to a real error. – Richard Pennington Mar 10 '10 at 13:03
  • @Richard, Thanks. So I should consider zero as error condition and close the connected socket. Right? – kumar Mar 10 '10 at 13:05
  • 6
    Yes, you should close the connected socket. However it is not an error. –  Mar 10 '10 at 13:26
  • 3
    @kumar No, you should consider -1 as an error and 0 as a normal disconnect, and close the socket in either case. – user207421 Jan 25 '16 at 11:22
  • 1
    just to add that if the buffer size you gave to read is 0, then the read will also return 0 even though the socket is not closed. – Itay Bianco Dec 05 '18 at 11:08
  • In this case, if I use epoll framework for monitoring fds, does it raise events such as EPOLLHUP or EPOLLERR in this particular case? – TheChosenOne Dec 03 '20 at 03:51