title: Multi Threaded TCP Server in C
body: <pre><code>int sock, connected, bytes_received, true = 1;
  struct sockaddr_in server_addr, client_addr;
  int sin_size;
  
  if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      perror("Socket");
      exit(1);
  }
  
  if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &amp;true, sizeof (int)) == -1) {
      perror("Setsockopt");
      exit(1);
  }
  
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(atoi(argv[1]));
  server_addr.sin_addr.s_addr = INADDR_ANY;
  bzero(&amp;(server_addr.sin_zero), 8);
  
  if (bind(sock, (struct sockaddr *) &amp;server_addr, sizeof (struct sockaddr))
          == -1) {
      perror("Unable to bind");
      exit(1);
  }
  
  if (listen(sock, 5) == -1) {
      perror("Listen");
      exit(1);
  }
  
  printf("\nTCPServer Waiting for client on port 5003");
  fflush(stdout); 
  
  while (1) 
  {
      pthread_t *child = (pthread_t *)malloc( sizeof(pthread_t) );
  
      sin_size = sizeof (struct sockaddr_in);
      connected = accept(sock, (struct sockaddr *) &amp;client_addr, &amp;sin_size);
      printf("\n I got a connection from (%s , %d)\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
  
      pthread_create(child, NULL, interpretMessage, NULL);
      free(child);
  }
  </code></pre>
  
  <p>My TCP server listens on port 5003. When a connection is made, I want to spawn a thread and run the function interpretMessage. I have a few questions about this...</p>
  
  <p>1) Am I doing calling malloc and free in the correct places?</p>
  
  <p>2) After pthread_create is called, does my code immediately jump to "free(child);" and then back to the beginning of the while loop?</p>
  
  <p>3) What happens if 5 people connect at the same exact time (how does the code run to spawn 5 threads?)</p>