title: Is this the correct way to close socket descriptors on fork?
body: <p>Consider this code:</p>
  
  <pre><code>socket_fd = start_server(port);
  
  while (1){
  
      new_socket_fd = accept_client(socket_fd);
  
      int pid = fork();
  
      if (pid == 0){
  
          //I am the child server process
  
          close(socket_fd);      &lt;------(1)
  
          do_stuff_with_client(new_socket_fd, buffer);
  
          close(new_socket_fd);       &lt;------(2)
  
          exit(0);
  
      } else if (pid &gt; 0){
  
          //I am the parent server process
  
          close(new_socket_fd);      &lt;------(3)
  
      } else {
  
          fprintf(stderr, "Fork error\n");
          return 1;
      }
  }
  </code></pre>
  
  <p>From what I understand, when a process calls fork(), its address space is duplicated but not shared, so if I change variables or close file descriptors from child's process, it doesn't affect the parent.</p>
  
  <p>That said, after the server has accepted a new connection (thus creating <code>new_socket_fd</code>) it forks itself, and the child closes <code>socket_fd</code> (1) because it's not required since the parent is still listening at its <code>socket_fd</code>. </p>
  
  <p>The child processes the requests and then closes its <code>new_socket_fd</code> (2) and exits.</p>
  
  <p>While the child is doing all of these, the parent process has already closed <code>new_socket_fd</code> (3) since the connection is being handled by the child.</p>
  
  <p>The question is: are these assumptions right? </p>