简体   繁体   中英

What does recv() return when using non-blocking sockets?

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) {
 ...
     }

}

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].

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM