title: Enable non-blocking socket
body: <p>I have a server written in C/C++.
  I set the wrapper for the connection as follow:</p>
  
  <pre><code>    //START WRAPPER
      void Server::init_address(int port)
      {
  memset(&amp;(this-&gt;serv_addr), 0, sizeof(this-&gt;serv_addr));
  this-&gt;serv_addr.sin_family = AF_INET;
  this-&gt;serv_addr.sin_port = htons(port);
  this-&gt;serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
      }
  
  
      int Server::w_socket()
      {
  int retv;
  retv = socket(PF_INET, SOCK_STREAM, 0);
  //FIXME
  //fcntl(retv, F_SETFL, O_NONBLOCK);
  if(retv == -1)
  {
      std::string err_msg(strerror(errno));
      err_msg = "[socket] " + err_msg;
      throw err_msg;
  }
  else
  {
      int reuse_opt = 1;
  
      if(setsockopt(retv, SOL_SOCKET, SO_REUSEADDR, &amp;reuse_opt, sizeof(int))==-1)
      {
          perror("setsockopt error");
          exit(1);
      }
      return retv;
  }
      }
  
      void Server::w_bind()
      {
  int retv;
  retv = bind(this-&gt;sock_fd,
          (struct sockaddr*) &amp;(this-&gt;serv_addr),
          sizeof(this-&gt;serv_addr));
  
  if(retv == -1)
  {
      std::string err_msg(strerror(errno));
      err_msg = "[bind] " + err_msg;
      throw err_msg;
  }
      }
  
      void Server::w_listen()
      {
  int retv;
  retv = listen(this-&gt;sock_fd, 3);
  if (retv == -1)
  {
      std::string err_msg(strerror(errno));
      err_msg = "[listen] " + err_msg;
      throw err_msg;
  }
      }
  
      int Server::w_accept(struct sockaddr_in* client_addr)
      {
  int retv;
  int socklen = sizeof(sockaddr_in);
  
  retv = accept(this-&gt;sock_fd, (struct sockaddr*)client_addr, (socklen_t*)&amp;socklen);
  if(retv == -1)
  {
      std::string err_msg(strerror(errno));
      err_msg = "[accept] " + err_msg;
      throw err_msg;
  }
  else
  {
      return retv;
  }
              }
  
      int Server::recvtimeout(int s, char *buf, int len, int timeout)
      {
  fd_set fds;
  int n;
  struct timeval tv;
  // set up the file descriptor set
  FD_ZERO(&amp;fds);
  FD_SET(s, &amp;fds);
  // set up the struct timeval for the timeout
  tv.tv_sec = timeout;
  tv.tv_usec = 0;
  // wait until timeout or data received
  n = select(s+1, &amp;fds, NULL, NULL, &amp;tv);
  if (n == 0){
      return -2; // timeout!
  }
  if (n == -1){
      return -1; // error
  }
  // data must be here, so do a normal recv()
  return recv(s, buf, len, 0);
      }
      // END WRAPPER
  </code></pre>
  
  <p>My goal is to enable the non-blocking socket mode.
  I've tried to do <strong>fcntl(retv, F_SETFL, O_NONBLOCK);</strong> like Beej manual said, but I receive the error: <em>[accept] Resource temporarily unavailable</em>
  A solution to this problem is using the <strong>select</strong> function, but I already use it in the recvtimeout function, always like Beej guide said.</p>
  
  <p>So, I don't know how to solve this problem to enable the non-blocking socket mode.</p>