title: Inherit parent socket in fork() child
body: <p>I m developing a C application running on linux system (<strong>kernel 3.4.11</strong>)</p>
  
  <p>In my application, I m opening a server socket on a thread. And I m opening a <code>fork()</code> in which I execute a shell command with <code>execvp()</code> in the main thread.</p>
  
  <p>Opening a <code>fork()</code> will inherit the socket file descriptor in the child. And this could cause problems according to many topics on the net. In my case If I close my application I can see with <code>netstat</code> that the socket is assigned to another daemon (another random daemon).</p>
  
  <p>In fact there is many solutions for a such issue:</p>
  
  <p><strong>1)</strong> close the socket on the beginning of the <code>fork()</code> child:</p>
  
  <pre><code>if ((pid = fork()) == -1)
      return -1;
  
  if (pid == 0) {
      /* child */
  
      close(socket_desc);
  </code></pre>
  
  <p><strong>2)</strong> Use <code>fcntl()</code> and <code>FD_CLOEXEC</code> when opening the socket in the parent</p>
  
  <pre><code>socket_desc = socket(AF_INET , SOCK_STREAM , 0);
  fcntl(socket_desc, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
  </code></pre>
  
  <p><strong>3)</strong> Use <code>O_CLOEXEC</code> in the <code>socket()</code> function:</p>
  
  <pre><code>socket_desc = socket(AF_INET , SOCK_STREAM|O_CLOEXEC , 0);
  </code></pre>
  
  <p>What's the best solution? and why?</p>
  
  <p>Any other better solution is welcome.</p>