I wrote a simple TCP network library with epoll
for linux.
In one of my tests, I want to test the throughput of the library. I send 2000000 msgs of 500 bytes.
The binded socket randomly returns zero on a recv
after 800000 or more msgs have been received.
Other times, all messages are received. What would cause this to happen?
The recv call is at line 393 of the sparrow.c
file.
I can verify that data_in->len > data_in->cur
int result = recv(sock->fd, data_in->data + data_in->cur, data_in->len - data_in->cur, 0); //On error or connection closed. //TODO We need to handle closed connections differently, possibly automatically reconnecting. if(result <= 0) { //TODO Make Dprintf printf("Receive error or we received a signal that the connection closed.nWe are closing the connection.n"); spev->error = 1; sparrow_socket_close(sp,sock); return 0; }
You can check the library here:
- https://github.com/xekoukou/sparrow
- https://github.com/xekoukou/sparrow/blob/master/thr_client.c
- https://github.com/xekoukou/sparrow/blob/master/thr_server.c
edit:
- I found the problems of the code. First there was a small part of the code that didn’t check for EAGAIN error. My code simply closed the connection because it considered it a non-recovering error.
- @EJP effectively answered the question. Recv returns zero only if the connection is closed or we have a zero sized buffer.
- Another interesting question is how to effectively debug when something happens in a loop on the 800000 iteration.
Advertisement
Answer
recv()
returns zero at end of stream, which in turn occurs when the peer closes the connection. There is nothing ‘random’ about it.