title: Linux daemonize without PID file race condition
body: <p>I have done work several times on making a program run as a daemon under Linux.</p>
  
  <ul>
  <li>In one case, I've just used <a href="http://man7.org/linux/man-pages/man3/daemon.3.html" rel="nofollow noreferrer"><code>daemon()</code></a>.</li>
  <li>On another occasion, I've written my own daemon code (<a href="http://www.microhowto.info/howto/cause_a_process_to_become_a_daemon_in_c.html" rel="nofollow noreferrer">based on something like this</a>) because I wanted to do more complicated redirection of STDIN, STDOUT, etc.</li>
  <li>I've also used the Busybox <a href="https://busybox.net/downloads/BusyBox.html#start_stop_daemon" rel="nofollow noreferrer"><code>start-stop-daemon</code></a> to start a C# Mono program as a daemon, and also generate a PID file with the <code>-m</code> option.</li>
  </ul>
  
  <p>The problem is, all of these solutions have a race condition on PID file creation, which is to say, the PID file is written by the program by its background process, some indeterminate time after the foreground process has exited. This is a problem e.g. in an embedded Linux if the program is started by an initscript, and then lastly a watchdog process is started which monitors the program is running by checking its PID file. In the C# Mono case using <code>start-stop-daemon</code>, I've had such a system get rebooted occasionally at start-up by the watchdog because the program's PID file hadn't yet been written by the time the watchdog process begins monitoring (surprising as that may be that this would ever happen in a practical scenario).</p>
  
  <p>How can a program be daemonized without a PID file race condition? That is, in such a way to guarantee that the PID file is fully created and written with the valid PID value when the foreground process exits.</p>
  
  <p>Note, this is made a little more difficult with the Linux daemon <a href="https://stackoverflow.com/a/5386753/60075">fork-setsid-fork idiom (to prevent the daemon from acquiring a controlling tty)</a>, because the parent can't so easily get the grandchild's PID.</p>