title: Understandng the reason for recv blocking forever
body: <p>I run a Linux program written in C that would periodically receive data by parsing an HTTP response, crunch some numbers and then report the result by HTTP GET of another web page.</p>
  
  <p>My problem is that sometimes, one of the instances would "freeze".</p>
  
  <p>Looking at <code>top</code> I can see that it is in <code>sk_wait_data</code> state and attaching a debugger reveals that it is blocked by a <code>recv</code> call.</p>
  
  <p>Here is a minimal version of the code that does the TCP connection (it was adapted from <a href="http://www.linuxhowtos.org/C_C++/socket.htm" rel="nofollow">http://www.linuxhowtos.org/C_C++/socket.htm</a>):</p>
  
  <pre class="lang-c prettyprint-override"><code>int connectTCP(const char* host, const char* page, int portno) {
      int sockfd;
  
      struct sockaddr_in serv_addr;
      struct hostent *server;
  
      // Create socket //
      sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      if (sockfd &lt; 0) 
          error("ERROR opening socket");
  
  
      // Get ip from hostname //
      server = gethostbyname(host);
      if (server == NULL)
          error("ERROR, can not find host\n");
  
      memset((char *) &amp;serv_addr, 0, sizeof(serv_addr));
  
  
      serv_addr.sin_family = AF_INET;
      memcpy((char *)&amp;serv_addr.sin_addr.s_addr,   // Destination
              (char *)server-&gt;h_addr,  // Source
              server-&gt;h_length);       // Size
      serv_addr.sin_port = htons(portno);
  
      // Conect to socket //
      if (connect(sockfd, (struct sockaddr *) &amp;serv_addr, sizeof(serv_addr)) &lt; 0) 
          error("ERROR connecting");
  
      return sockfd;
  
  }
  
  char* httpGet(const char* host, const char* page, int portno) {
    int sockfd, n;
  
    sockfd = connectTCP(host, page, portno);
    memset(buffer, 0, sizeof(buffer));
  
    sprintf(buffer, "GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n", page, host);
  
    n = send(sockfd,buffer,strlen(buffer), 0);
  
    if (n &lt; 0) 
      error("ERROR writing to socket");
  
    int count = 0;
    do {
      n = recv(sockfd, buffer + count, BUFFER_MAX_SIZE - count, 0);
      if (n &lt; 0) {
        error("ERROR reading from socket");
  
      }
  
      count += n;
    } while(n != 0);
  
    close(sockfd);
  
    return buffer;
  }
  </code></pre>