Making a Better Daemon

Author: Geo Carncross
Date: March 16, 2006

-P: [pre]fork processes for handling children

-D: detach from console by closing fds 0..93 inclusive after starting

-B: put dbmail in the background (because for some reason you're starting dbmail from something that isn't a shell and you can't use &)

-G: start dbmail in its own process group (setpgid) so that stupid programs (like pppd) don't kill it when a user disconnects- even more useful if someone starts it from a serial console and has a SAK

-S: start dbmail in its own session (setsid)- implies -G, and requires -D (and the operations performed by -D must be done before setsid())

None of these definitions are negative; none of these switches “stop” dbmail from doing something. That's confusing.

If the “default” should be something else, I recommend using a wrapper script as I described earlier.

> It would kinda neat if you ran 'dbmail-imapd' and the program returned

“Dbmail-IMAPd ready to rock” and started speaking IMAP to you ;-) I'm
not sure if I like this, though. I'll marinate with it some more.

Supporting imap preauth isn't such a bad idea- it makes it so people can ssh-tunnel their IMAP mail without having to do port forwarding.

As a side note- there's a reason I listed fds 0..93 as should be closed by -D; I'm sure everyone guesses 0 through 2 easily enough, but there might be some pipelines, so close a bit further- fds 15 or 16 is usually what I see.

The Bourne shell (the REAL one) uses file descriptor 19 internally for reading scripts- we shouldn't close it in the parent- but after forking (-P) because the script running dbmail might not end in:

      exec dbmail-start ....

but instead expect to be able to do some things afterwards.

HP-UX uses file descriptor 59 instead of file descriptor 19, but for the same reason.

I've heard reports of shells in this era using a descriptor as high as 92- but as you already know- I treat the detaching from the console as a significantly system-dependant, and non-portable thing, such that I let the administrator do it in the shell if they know they're using such a beast.

Besides, THESE days, UNIX has close-on-exec (or ioctl FIOCLEX), so the shell doesn't need to use magic file descriptors anymore.

so if -S is set and -D isn't,
      if we have FIOCLEX defined, or FD_CLOEXEC,
              setsid() will do the right thing
      otherwise, we need to close all file descriptors 0..93
otherwise if -D is set,
      we need to close all file descriptors 0..93

of course, if we DON'T have FD_CLOEXEC, then chances are we don't have setsid() either (FD_CLOEXEC and setsid() are both in POSIX 1003)- so really, this is more of a historical footnote- especially in case anyone wants to port dbmail to a V7 machine :)

 
daemonize.txt · Last modified: 2012/02/27 21:44 by bas
 
DBMail is developed by Paul J Stevens together with developers world-wide