title: Non-Blocking TCP Socket hangs when timespec initialized (C++)
body: <p>I have a tcp server running on my localhost.  My program connects to this tcp server, which responds with data on connection.  I'm using signals elsewhere in the program, so I need this to be non-blocking.
  Unfortunately, I also need to use <code>clock_gettime</code>.  When I do this, the tcp connection hangs.
  The only alternatives that I can think of are to use pipes, switch over to udp, but those two are not desired results.
  Relevant code below:</p>
  
  <h2>tcpsens.h:</h2>
  
  <pre><code>....
  std::string tcpsens::getstr(void){
      int outsock;
      struct sockaddr_in servaddr;
      outsock = socket(AF_INET,SOCK_STREAM,0);
  
      bzero(&amp;servaddr,sizeof(servaddr));
      servaddr.sin_family = AF_INET;
      servaddr.sin_addr.s_addr = ip_addr;
      servaddr.sin_port=htons(port);
  
      if (fcntl(outsock, F_SETFL, O_NDELAY | O_NONBLOCK) &lt; 0) {
              perror("Can't set socket to non-blocking");
              exit(0);
          }
  
      connect(outsock, (struct sockaddr *)&amp;servaddr, sizeof(servaddr));
      while(1) {
          buflen=recv(outsock,buf,255,0);
          if (buflen&gt;0){
              buflen=-1;}
          else if (buflen==0){
              break;}
          //sleep(1);
          //printf("still looping.\n");
      }
      close(outsock);
      return buf;
  }
  float tcpsens::gettruespeed(){
      float speed,val;
      buffer = getstr();
      sscanf(buffer.c_str(),"%f,%f\n",&amp;speed,&amp;val);
      return speed;}
  ...
  </code></pre>
  
  <h2>testtcp1.cpp</h2>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include "tcpsens.h"
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;sys/time.h&gt;
  #include &lt;time.h&gt;
  
  
  int main(void){
          //timing functions
          //struct timespec timer;
  
          // initialize the tcpsensor
          tcpsens t;
  
          // connect to tcp and get sensor and speed reading
          std::cout &lt;&lt; "TEST WITHOUT INITIALIZING TIMESPEC:\n\n";
          std::cout &lt;&lt; "expecting value of ~0.00, got " &lt;&lt; t.gettruespeed() &lt;&lt; "\n";
          std::cout &lt;&lt; "expecting value ~0.00, got " &lt;&lt; t.getsensval() &lt;&lt; "\n";
  
          return 0;
  }
  </code></pre>
  
  <p>compiled with <code>$ g++-4.7 -std=c++11 testtcp1.cpp -lrt</code>, gives result</p>
  
  <pre><code>$ ./a.out
  TEST WITHOUT INITIALIZING TIMESPEC:
  
  expecting value of ~0.00, got 0
  expecting value ~0.00, got 0
  </code></pre>
  
  <h2>testtcp2.cpp</h2>
  
  <p>same as testtcp1.cpp except uncommented the line <code>struct timespec timer;</code>, and changing the message. gives result</p>
  
  <pre><code>$ ./a.out
  TEST WITH INITIALIZING TIMESPEC:
  </code></pre>
  
  <p>and hangs forever.</p>