c++ ServerSocket(), FD_CLOEXEC, fork() & excel()
<p>I had issues trying to background a command in my app, so I was <a href="http://stackoverflow.com/questions/8888563/c-fork-execl-dont-wait-detach-completely">told here</a> to double fork and clear some of the settings, so this was my result:</p>

<pre><code>if((pid = fork()) &lt; 0)
    perror("Error with Fork()");
else if(pid &gt; 0) {
    return "";
}
if (setsid()==-1) {
    Log("failed to become a session leader");
}

if (chdir("/") == -1) {
    Log("failed to change working directory");
}

umask(0);
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
if (open("/dev/null",O_RDONLY) == -1) {
    Log("failed to reopen stdin");
}
if (open("/dev/null",O_WRONLY) == -1) {
    Log("failed to reopen stdout");
}
if (open("/dev/null",O_RDWR) == -1) {
    Log("failed to reopen stderr");
}

signal(SIGHUP, SIG_IGN);
Log("No return, forking..");
if((pid = fork()) &lt; 0)
    perror("Error with Fork()");
else if(pid &gt; 0) {
    return "";
} else {        
    if(execl("/bin/bash", "/bin/bash", "-c", cmddo, (char*) 0) &lt; 0) perror("execl()");
    exit(0);
}
</code></pre>

<p>Double forking fixed the issue of the execl'd proc stopping when its parent is closed but it left me with the execl'd process holding onto the parents socket, so when the parent tries to start again it can't.</p>

<p>Here is my parent socket stuff:</p>

<pre><code>ServerSocket server(listenport);
while(true)
{   
    ServerSocket* new_sock = new ServerSocket();

    server.accept (*new_sock);

    pthread_t thread;
    int rc = pthread_create(&amp;thread, NULL, &amp;LoadThread, (void*)(new_sock));

    if (rc) Log_warn("Fatal Error: pthread_create() #%d", rc);
    pthread_detach(thread);
}
</code></pre>

<p>I was told to FD_CLOEXEC on the socket in my last question but I do not understand how-to do that - and google (plus stack) isn't showing me much help in regards to that.</p>

<p>How do I FD_CLOEXEC on my ServerSocket() so when I fork/execl a sub process it won't hang my socket?</p>

<p>Thanks :D</p>

<p><strong>ANSWER</strong>:
As told below to clear the fd's out - my code actually had this, and it worked for me:</p>

<pre><code>struct rlimit       rl;
int                 i;

if (rl.rlim_max == RLIM_INFINITY)
  rl.rlim_max = 1024;

for (i = 0; (unsigned) i &lt; rl.rlim_max; i++)
  close(i);
</code></pre>
