(Related to: approx. 1000 questions related to daemonizing a process.)
I've been doing double-fork forever on the base "because Stevens says so".
This works, of course, and 99.9% of the time it makes no noticeable difference, but it is slightly less efficient than I'd like for a daemon process that should start (and shutdown/restart) as fast as possible with as little downtime in between as can be achieved.
No, fork
still is not precisely a lightweight syscall, so if there is no absolutely urgent reason of doing it twice, I'd be most happy to skip it once.
I understand the purpose of a single fork with the intermediate parent exiting (technically, that's already two forks, one being done by the shell), this orphans the daemon process, makes init adopt it, and allows a presumed shell to return to the prompt (or continue executing a batch file, whatever).
setsid()
will now place the daemon process in a new session, so by definition it will be in a session different from the one used by the terminal. You care about that because closing the shell/terminal would kill the daemon otherwise, which is arguably undesirable.
The daemon process is now also the session leader (and process leader, and sole process) of that new session.
Now... you are to fork a second (actually, third) time to guarantee that the daemon is not the session leader because this is apparently a bad thing. It's a bit difficult to find a good explanation as to why it is a bad thing, but presumably it allows opening a terminal by accident and making it the controlling terminal of the daemon. Which, I guess, would again mean having it killed when that terminal is closed.
Here we are at the part that I don't understand. Out of the blue, I wouldn't even know how to open a controlling terminal (open /dev/tty
?), nor why I'd want to do this, nor how it could happen accidentially, even more so as chroot
will make it somewhat difficult to open haphazard files in /dev
even deliberately, assuming that e.g. a daemon naively opens files based on non-validated user requests and you're trying to be purposely malicious.
Thus, what exactly am I trying to defend against with this second fork? Is being a session leader actually a practical, not-entirely-theoretical issue at all?