title: Sockets and threads using C
body: <p>I am new to both sockets and threads. I have this code:</p>
  
  <pre><code>listen(socket_fd, 20);
  
  /* Looooop */
    while (1) {
      newsocket_fd = accept(socket_fd, 
                            (struct sockaddr *) &amp;client_addr, 
                            &amp;client_len);
      if (newsocket_fd &lt; 0) {
        error("ERROR on accept");
      }
      pthread_t thread;
      pthread_create(&amp;thread, NULL, run_thread, (void *) newsocket_fd);
      pthread_join(thread, NULL);
    }
  </code></pre>
  
  <p>How can I start a new thread for each new connection, rather than for each request? These threads should be started when a new connection comes in, and these threads should then wait for requests, handle those requests, and finally return when the connection is closed. <strong>There should be one thread for each connection.</strong> Here is the code for <code>run_thread</code>:</p>
  
  <pre><code>void
  *run_thread(void *ptr) {
    char buffer[256];
    bzero(buffer, 256);
    int n;
    n = read((int) ptr, buffer, 255);
    if (n &lt; 0) error("ERROR Reading from socket");
    printf("%s\n\n**********\n\n", buffer);
  
    /* Parse buffer and return result */
    char *result;
    {
      /* First, determine command, 4 characters */
      /* (much code) */
    }
  
    n = write((int) ptr, result, strlen(result));
    if (n &lt; 0) error("ERROR Writing to socket");
  }
  </code></pre>
  
  <p>Can anyone help me? Thanks.</p>