By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,192 Members | 852 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,192 IT Pros & Developers. It's quick & easy.

Recv timeout on non-blocking socket

P: 3
On Linux (Ubuntu) I'm trying to figure out how to avoid recv() calls that hang forever by using using a non-blocking socket along with the select() function. This seems to be the standard way to avoid recv() calls that hang forever.

I'm having difficulty getting this to work however. It seems to work sometimes, but occasionally the recv() call hangs. Additionally, I think the loop I'm using is not doing something right, because it slows down the system indicating it is using a lot of CPU cycles.

Here is the recv() function I used:
Expand|Select|Wrap|Line Numbers
  1.       bool recv_non_block(char* buf)
  2.       {      
  3.             int status;
  4.             do {
  5.                   if ((status = recv(m_sock, buf, RECV_BUF_SIZE, 0)) == -1) {
  6.                         if (errno == EWOULDBLOCK || errno == EAGAIN) {
  7.                               if (Select()) continue;
  8.                         }
  9.                         else return false;
  10.                   }
  11.             } while (status != 0);
  12.             return true;
  13.       }
  14.  
Note: The Select() function is simply a convenient wrapper for the select() function call.

Is the above loop a correct way to receive on a non-blocking socket? Note also that since this can be used on an Internet website, I do not necessarily know the size of the data I am receiving, and therefore I need to rely on recv() returning 0 in order to end the loop.
Mar 19 '07 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.