title: Closing the listening socket after a fork()
body: <p>A common server socket pattern on Linux/UNIX systems is to listen on a socket, accept a connection, and then <code>fork()</code> to process the connection.</p>
  
  <p>So, it seems that after you <code>accept()</code> and <code>fork()</code>, once you're inside the child process, you will have inherited the listening file descriptor of the parent process.  I've read that at this point, you need to close the listening socket file descriptor from within the child process.</p>
  
  <p>My question is, why?  Is this simply to reduce the reference count of the listening socket?  Or is it so that the child process itself will not be used by the OS as a candidate for routing incoming connections?  If it's the latter, I'm a bit confused for two reasons:</p>
  
  <p>(A) What tells the OS that a certain process is a candidate for accepting connections on a certain file descriptor?  Is it the fact that the process has called <code>accept()</code>?  Or is it the fact that the process has called <code>listen()</code>?</p>
  
  <p>(B) If it's the fact that the process has called <code>listen()</code>, don't we have a race condition here?  What if this happens:</p>
  
  <ol>
  <li>Parent process listens on socket S. </li>
  <li>Incoming connection goes to Parent Process.</li>
  <li>Parent Process forks a child, child has a copy of socket S</li>
  <li><em>BEFORE</em> the child is able to call <code>close(S)</code>, a <em>second</em> incoming connection goes to Child Process.  </li>
  <li>Child Process never calls <code>accept()</code> (because it's not supposed to), so the incoming connection gets dropped</li>
  </ol>
  
  <p>What prevents the above condition from happening?  And more generally, why should a child process close the listening socket?</p>