note
afoken
<blockquote>
<ol>
<li>Check for existence and program access to:
<ul>
<li>PID directory (typically /var/run or /usr/local/var/run)</li>
<li>Log file directory</li>
<li>Data file directory</li>
<li>Other system resources (network ports, specific hardware)</li>
</ul>
</li>
<li>Reset user credentials (first reset group ID, then user ID)</li>
<li>Create PID file and lock for exclusive access.</li>
<li>Open log file(s)</li>
<li>Allocate resource(s)</li>
</ul>
</blockquote>
<p>Are you aware that this still has a race condition? You run a lot of tests in step 1, most of those tests involve system calls. Step 2 has two system calls. Each and every system call may cause a task switch to a malicious program that -- with a little bit of luck and good timing -- can change what you checked for in step 1, causing the following steps to fail rather unexpectedly. And each and every system call may cause a task switch to a second instance fighting for the PID file.</p>
<p>Daemons do not need PID files, and most daemons contain code that they don't really need, for backgrounding, logging, restarting, dropping privileges, and to prevent multiple instances. The [http://cr.yp.to/daemontools.html|daemontools] reduce code complexity in daemons and they take care of backgrounding, logging, restarting, dropping privileges, and single instances. Even communication via signals works completely without PID files (with a patch, SIGUSR1 and SIGUSR2 can also be sent). Daemontools may look strange, and some of DJBs decisions (errno, location in filesystem, ...) may cause a little bit of confusion, but once you unterstand what happens, the daemontools are the most natural way to implement daemons on Unix and derivates.</p>
<p>Alexander</p>
<div class="pmsig"><div class="pmsig-747201">
--<br>
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
</div></div>
841112
841157