Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can read() function on a connected socket return zero bytes?

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?

like image 248
kumar Avatar asked Mar 10 '10 12:03

kumar


People also ask

What is the return value of read in C?

In the absence of errors, or if error detection is not performed, the read() function shall return zero and have no other results.

Under which of the following circumstances recv () returns a zero value?

A returned value of zero indicates one of the following: The partner program has sent a NULL message (a datagram with no user data), A shutdown() to disable reading was previously done on the socket. The buffer length specified was zero.

How does socket read work?

It reads input from the user on the standard input stream, and then forwards that text to the echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server.

What does it mean when recv returns 0?

Upon successful completion, recv() returns the length of the message in bytes. If no messages are available to be received and the peer has performed an orderly shutdown, recv() returns 0. Otherwise, -1 is returned and errno is set to indicate the error.


1 Answers

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

like image 138
user184968 Avatar answered Oct 11 '22 20:10

user184968