title: Multi-threaded udp server/client
body: <p>I just created a little reliable file transfer using udp but it only handles one client. So I thought about using fork() to get the server to handle multiple clients. But, i don't really know how to proceed. For now, I know I don't need to change the client side and the server is the one that will do the dirty work. Any thought/ideas on how to tackle that problem is greatly appreciated.
  Ps. here is how I started:</p>
  
  <pre><code> void sigchldAction(int sig) {
   while (waitpid(-1, 0, WNOHANG) &gt; 0) {
       ;
   }int main(int argc, char *argv[]) {
  
   return;
  } //This is my function that waits for all the processes 
  </code></pre>
  
  <p>Here is my server:</p>
  
  <pre><code>int main(int argc, char *argv[]) {
      struct sockaddr_in serv_addr;
      int port_number, socket_fd;
      port_number = atoi(argv[1]);
  
      signal(SIGCHLD, sigchldAction);
  
      if ((socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) &lt; 0)  exit(EXIT_FAILURE);
      if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR,
   (const void *)&amp;optval, sizeof(int)) &lt; 0) exit(EXIT_FAILURE);
  
      bzero((void *)&amp;serv_addr, sizeof(struct sockaddr_in));
      serv_addr.sin_family = AF_INET;
      serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
      serv_addr.sin_port = htons(port_number);
      if (bind(socket_fd, (struct sockaddr *)&amp;serv_addr,
           sizeof(struct sockaddr_in)) &lt; 0) exit(EXIT_FAILURE);
  
      pid_t child_pid;
      while (1) {
      child_pid = fork();
  
      switch (child_pid) {
          case -1:
              perror("Fork() Failed. \n");
              exit(EXIT_FAILURE);
              break;
          case 0:
              process_request(socket_fd);
              exit(EXIT_SUCCESS);
              break;
          case 1:
              close(socket_fd);
              break;
  
      } 
  
  }
      close(socket_fd);
  exit(EXIT_SUCCESS);
  }
  </code></pre>
  
  <p>Then my process_request function takes care of any incoming data.</p>