title: nonblocking TCP socket continuously receive EAGAIN on read()
body: <p>The TCP socket has been set to nonblocking.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>char * recv_response(int sockfd)
  {
      char * resp_msg = (char *)malloc(MAX_RESP_LEN);
  
      int n, len;
      len = 0;
      while (1) {
          n = read(sockfd, resp_msg + len, 1024);
          printf("#recv_response. n = %d, len = %d#\n", n, len);
          if (n &lt; 0) {
              if (errno == EAGAIN || errno == EWOULDBLOCK) {
                  printf("#recv_response. errno = EAGAIN#\n");
                  sleep(5);
                  continue;
              }   
              else if (errno == EINTR) {
                  printf("recv interruputed\n");
                  close(sockfd);
                  return NULL;
              }   
          }   
          else if (n == 0)  
              break;
          else
              len += n;
      }   
      close(sockfd);
      resp_msg = realloc(resp_msg, len + 1); 
      return resp_msg;    
  }
  </code></pre>
  
  <p>And here's how it works when sending GET request to a webpage:</p>
  
  <pre><code>#recv_response. n = -1, len = 0#
  #recv_response. errno = EAGAIN#
  #recv_response. n = 1024, len = 0#
  #recv_response. n = 1024, len = 1024#
  #recv_response. n = 1024, len = 2048#
  #recv_response. n = 1024, len = 3072#
  #recv_response. n = 1024, len = 4096#
  #recv_response. n = 909, len = 5120#
  #recv_response. n = -1, len = 6029#
  #recv_response. errno = EAGAIN#
  #recv_response. n = -1, len = 6029#
  #recv_response. errno = EAGAIN#
  #recv_response. n = -1, len = 6029#
  #recv_response. errno = EAGAIN#
  #recv_response. n = -1, len = 6029#
  #recv_response. errno = EAGAIN#
  ^C
  </code></pre>
  
  <p>The <code>read()</code> should return n=0 to stop the while loop after all stuff in the webpage is read. But here it's not.</p>
  
  <p>UPDATE:
  The above failure case happens when I tested this code in office. When I came back to home it works:</p>
  
  <pre><code>#recv_response. n = -1, len = 0#
  #recv_response. errno = EAGAIN#
  #recv_response. n = 1024, len = 0#
  #recv_response. n = 1024, len = 1024#
  #recv_response. n = 1024, len = 2048#
  #recv_response. n = 1024, len = 3072#
  #recv_response. n = 1024, len = 4096#
  #recv_response. n = 227, len = 5120#
  #recv_response. n = 0, len = 5347#
  HTTP/1.1 200 OK
  </code></pre>
  
  <p>I know that firewalls in company network may ban some network services like <code>ping</code>, but why here the <code>read()</code> can read stuff but can't stop?</p>