Reputation: 703
If I set a socket to non-blocking, what should I get from recv() if there is no new data to be read?
At the moment, I am using and if statement to see if I received anything greater than -1. But it seems to block somehow if nothing is received. This is what my code looks like:
flags = fcntl(newfd, F_GETFL);
flags |= O_NONBLOCK;
fcntl(newfd, F_SETFL, flags);
while(1){
...
...
if( (recvBytes = recv(newfd, recvBuf, MAXBUFLEN-1, 0)) > -1) {
...
}
}
Upvotes: 1
Views: 1522
Reputation: 3807
I would suggest the following superficial change. It doesn't change the logic of your code but it does make it very clear what is being tested, when and what for.
int response;
...
while(1){
...
response = recv(newfd, recvBuf, MAXBUFLEN-1, 0);
if (response <= 0)
{ // assuming that a zero or negative response indicates
// test errno for EAGAIN or EWOULDBLOCK per JB comment
...
} else {
// response contains number of bytes received..
}
...
} // end while
A good compile will optimize the assignment and if statement into something like you originally wrote. So this style of coding is to make it easy to think about what the code does.
Upvotes: 2
Reputation: 42094
According to my manpage:
If no messages are available at the socket and O_NONBLOCK is not set on the socket's file descriptor, recv() shall block until a message arrives. If no messages are available at the socket and O_NONBLOCK is set on the socket's file descriptor, recv() shall fail and set errno to [EAGAIN] or [EWOULDBLOCK].
Upvotes: 4