What is the correct order for daemonising on Linux?
<p>I've written my first Daemon and its working correctly. However all the tutorials I've followed differ slightly and I'm concerned that the steps I've used in the daemonising process could be reordered and it would still work.</p>

<p>The intention is for this daemon to be managed by init (we're on an old server), so it will be started as root and needs to drop privileges.</p>

<p>So far my order is:</p>

<ol>
<li>Start the syslogger</li>
<li>Create an file in /var/run which will become a pid lockfile. Change file permissions to the daemon user. This is done before dropping privileges other wise the process would not have access to /var/run.</li>
<li>Check a flag to see if the process is already daemonised. This means if my daemonise function is called twice for any reason it wont try and spawn another child process.</li>
<li>Fork the process. Check for errors and exit the parent process.</li>
<li>Drop root privileges and become the daemon user.</li>
<li>Try and open the pid file and get a lock to confirm that there are no other instance of the daemon already running. Then write the current process id to the pid file.</li>
<li>Get a new session for the child/daemon process.</li>
<li>Set the umask</li>
<li>Change to the root directory - I think this is to prevent the directory the daemon was started in being indefinitely locked by the daemon process.</li>
<li>Reopen all file descriptors and send them to /dev/null - this means the standard streams have somewhere to go when the process is detached.</li>
<li>Set up signal handlers for the daemon process.</li>
<li>Set the daemonised flag</li>
</ol>

<p>It feels to me as through steps 5 through 11 could be done in any order. Part of my reasoning for the order above is that I want to drop root privilege as soon as I no longer require it.</p>

<p>In some examples I've seen the parent process wait for the child process to signal that its set up OK before exiting. Should I do this? What would happen if the parent exits before the child has got its own session and set up the file descriptors?</p>

<p>I guess I'm asking, what should the order of events be when setting up a daemon.</p>