I'm writing my own web server in C. And I'm kind of stuck with an annoying problem. I'm waiting for incoming connections like this:
struct sockaddr_in caddr;
uint32_t caddr_len = sizeof(caddr);
int fd = accept(sfd, (struct sockaddr *)&caddr, &caddr_len);
if(fd < 0) {
err(EXIT_FAILURE, "accept()");
}
And when accept()
succeeded, I'm starting to receive the data with:
errno = 0;
ssize_t r = recv(fd, buf, sizeof(buf), 0);
Sometimes it happens that I don't receive any data, when accessing with firefox.
When I set the timeout to 1s, errno
is set to EAGAIN
.
And when I set the timeout to 5s, errno
will not be set but I still not receiving any data r == 0
.
Is it possible to configure the socket so that accept()
only returns when there is actual data available?
Note: I do not experience this behavior when accessing with Chrome.
EDIT: Some suggested that I should use poll()
When I use poll()
, I have the same problem:
struct pollfd p[] = {{sfd, POLLIN}};
int r = poll(sfd, 1, 1000);
if(r <= 0) err("poll() -> %d", r);
r == 1
, but I have still the same problem, because this poll()
applies only to the listening socket. It doesn't tell me if there is actual payload when accepting.