In this answer, it is mentioned in passing that it is not appropriate for a daemon process to reparent itself to init
with the double-fork-and-exit trick. The answer links to a website which is no longer live but I found it on the Internet Archive. It lists a number of reasons for this which boil down to "You should not daemonize because it might break init
or other tools that don't expect daemonizing, and if someone is running it interactively, they should use &
or nohup
to explicitly ask for backgrounding." These reasons do sound rather convincing, actually, since a properly-configured daemon should already be running in a sane environment by the time it receives control. (Well, ideally it's running in a container with lots of fancy automation, but that's another story.)
However, I don't understand why we have setsid(2)
if we're not supposed to use it. I can understand setpgid(2)
; you need that to implement a (modern(ish)) shell, but it seems like the only way to reliably call setsid(2)
is to daemonize, and the man page even tells you to do this. I suppose you might use it to implement various low-level tools which eventually run login(1)
, but setsid(2)
is not a privileged system call and its man page makes no mention of this use case. The Python folks, at least, seem to think daemonizing includes reparenting, and I've seen this attitude in a number of other contexts (particularly academia, such as the textbook which that PEP cites).
As yet another point of reference, daemonize(1)
and daemon(3)
are things (on some systems), and the former's man page says this:
Most programs that are designed to be run as daemons do [various things including reparenting] for themselves. However, you'll occasionally run across one that does not. When you must run a daemon program that does not properly make itself into a true Unix daemon, you can use daemonize to force it to run as a true daemon.
What is the correct behavior for a daemon on startup, and in particular, should it reparent itself?
systemd
orsysvinit
or...), the OS... a good daemon may need to be written to handle multiple models, perhaps selected via command line flags. – Stephen Harris Jul 24 '16 at 12:12