title: Forking a process with threads containing sockets in C++
body: <p>I have the following C++ - scenario under CentOS.</p>
  <p>Process P1 contains:</p>
  <ul>
  <li>passive listening socket with descriptor D1.</li>
  <li>1 incoming connection (socket with D2).</li>
  <li>1 outgoing connection (socket with D3).</li>
  <li>thread T1 with 1 outgoing connection (socket with D4).</li>
  </ul>
  <p>Incoming socket connections are created with:</p>
  <ol>
  <li>socket( AF_INET,SOCK_STREAM,0 );</li>
  <li>setsockopt( ...SO_REUSEADDR, ...);</li>
  <li>bind</li>
  <li>listen</li>
  <li>accept</li>
  </ol>
  <p>Outgoing socket connections are created with:</p>
  <ol>
  <li>socket(AF_INET, SOCK_STREAM,0);</li>
  <li>connect</li>
  </ol>
  <p>Process P1 is now forked to P2 and in P2 there should be a
  new outgoing connection in a new thread T2. I am not interested in the other old connections here.</p>
  <p>What exactly do I have to consider here after the fork in P2? What are the best practices here? Are all my assumptions correct? I would realize it like the following:</p>
  <p>After the fork</p>
  <ul>
  <li>I close D1 in P2 directly, because I don't want to listen in different processes at the same port, although this would be possible. Correct?</li>
  <li>Because all FD's were copied (Ref-Counted?), I can safely close D2 and D3 in P2 without endangering the communication in P1, right?</li>
  <li>T1 is &quot;dead&quot; when forking anyway and so I should close D4 in P2 here too, or?</li>
  <li>Finally, I can spawn T2 in P2 and create a new outgoing socket D5 there</li>
  </ul>
  <p>Would a following scenario also be possible where I want to reuse D4?</p>
  <p>After the fork</p>
  <ul>
  <li>I close D1 in P2 directly</li>
  <li>I close D2 and D3 in P2</li>
  <li>T1 is &quot;dead&quot; but I do not close D4 in P2</li>
  <li>I spawn T2 and share the usage of D4 together with T1 from P1. Is this race-conditon-safe? Is this a good/common practice/pattern?</li>
  </ul>
  <p>General question:</p>
  <p>If the live-time of P2 is always shorter than of P1
  are not all descriptors automatically released/counted down
  after P2 terminates? Do I need to close any FD's in this case?</p>