I've implemented a web server in C. It calls recv()
on a connected, blocking socket to receive an incoming HTTP request. The Linux man pages state the following about recv()
on a blocking socket:
If no messages are available at the socket, the receive calls wait for a message to arrive...The receive calls normally return any data available, up to the requested amount, rather than waiting for receipt of the full amount requested.
...
These calls return the number of bytes received, or -1 if an error occurred...The return value will be 0 when the peer has performed an orderly shutdown.
Hence, to receive the full request, my server code contains a loop of the following form:
int connfd; // accepted connection
int len; // # of received bytes on each recv call
...
while (/* HTTP message received so far has not terminated */) {
len = recv(connfd, ...);
if (len == 0) {
// close connfd, then escape loop
} else if (len < 0) {
// handle error
} else {
// process received bytes
}
}
My question: is it possible for recv()
to return 0 bytes due to network issues and without the client performing an orderly shutdown, thereby causing my code to exit the loop prematurely? The man pages are ambiguous.