title: How to correctly use socket close for fork?
body: <p>I have questions about how to correctly close the socket file descriptor. Let's assume the server forks another procedure whenever it accepts a new connection. The original socket file descriptor is <code>sockfd</code> and the new socket file descriptor is <code>new_sockfd</code>.</p>
  
  <pre><code>sockfd = socket(...)
  bind(...);
  listen(...);
  
  while(1) {
    new_sockfd = accept(...);
    if(fork() == 0) {
      // Child process
      dosomething(...);
  
    }
    else {
  
    }
  }
  </code></pre>
  
  <p>My question is, where we should put <code>close(sockfd)</code> and <code>close(new_sockfd)</code>. I have seen some examples in the website (<a href="http://www.tutorialspoint.com/unix_sockets/socket_quick_guide.htm">http://www.tutorialspoint.com/unix_sockets/socket_quick_guide.htm</a>  "Handle Multiple Connection") they put <code>close(sockfd)</code> inside the <code>if</code> block and <code>close(new_sockfd)</code> in the <code>else</code> block. But, after the fork, aren't the two processes running in parallel? If parent process closes the <code>new_sockfd</code>, won't it affect the child process to handle the socket? Also, if child process executes <code>close(sockfd)</code>, won't this affect the entire socket program?</p>