title: How to use select and FD_SET in socket programming?
body: <p>I am new to socket programming, and I am having trouble understanding how <code>select()</code> and <code>FD_SET()</code> works.</p>
  
  <p>I modify an example from Beej's tutorial in an attempt to figure it out. What I want to do in the for loop is at each iterations I wait for 4 seconds. If a read is available, I would print "A key was pressed" and if it timeout, then it would print "Timed out." Then I would clear the set and repeat the process 9 more times. But it seems that once file descriptor 0 is set, it never gets unset even after a call to <code>FD_ZERO()</code> and/or <code>FD_CLR()</code>. In other words after I press a key in the first iteration of the loop the file descriptor is set for the rest of the iterations and no more waiting is done. So there must be something I am missing, but I don't know what.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;errno.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  #include &lt;arpa/inet.h&gt;
  #include &lt;netdb.h&gt;
  
  #define SERVERPORT 4950
  
  int main(int argc, char *argv[]) {
      struct sockaddr_in their_addr; // connector's address information
      struct hostent *he;
      int numbytes;
      int broadcast = 1;
  
      if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info
          perror("gethostbyname");
          exit(1);
      }
  
      // this call is what allows broadcast packets to be sent:
      if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &amp;broadcast,
          sizeof broadcast) == -1) {
          perror("setsockopt (SO_BROADCAST)");
          exit(1);
      }
      their_addr.sin_family = AF_INET;     // host byte order
      their_addr.sin_port = htons(SERVERPORT); // short, network byte order
      their_addr.sin_addr = *((struct in_addr *)he-&gt;h_addr);
      memset(their_addr.sin_zero, '\0', sizeof their_addr.sin_zero);
  
      struct timeval tv;
      fd_set broadcastfds;
  
      int i;
      for(i=0; i &lt; 10; i++) {
          tv.tv_sec = 4;
          tv.tv_usec = 500000;
  
          FD_ZERO(&amp;broadcastfds);
          FD_CLR(0, &amp;broadcastfds);
          FD_SET(0, &amp;broadcastfds);
          if(select(0+1, &amp;broadcastfds, NULL, NULL, &amp;tv) == -1) perror("select");
  
          if (FD_ISSET(0, &amp;broadcastfds)) printf("A key was pressed!\n");
          else printf("Timed out.\n");
          fflush(stdout); 
      }   
      close(sockfd);
      return 0;
  }
  </code></pre>