I've been looking at creating Unix dæmons, and there seem to be two methods. The long-winded one, which seems to come up when searching is to call fork()
, setsid()
, fork()
again, chdir()
to somewhere safe, set umask()
and, finally, close()
stdin
, stdout
and stderr
.
Running man daemon
, however, brings up information on a daemon()
function, which seems to do all the same stuff as above. Are there any differences between the two approaches or is daemon()
just a convenience function that does the same thing as the long-winded method? Is either one better, especially for a novice C programmer?
A daemon is a long-running background process that answers requests for services. The term originated with Unix, but most operating systems use daemons in some form or another. In Unix, the names of daemons conventionally end in "d". Some examples include inetd , httpd , nfsd , sshd , named , and lpd .
They are utility programs that run silently in the background to monitor and take care of certain subsystems to ensure that the operating system runs properly. A printer daemon monitors and takes care of printing services.
Daemons are started by the init process, which means they have a PPID of 1.
A daemon is usually created either by a process forking a child process and then immediately exiting, thus causing init to adopt the child process, or by the init process directly launching the daemon.
The daemon
function is not defined in POSIX, so its implementation (if any) could behave differently on different platforms.
On Linux with glibc, daemon
only does one fork, optionally chdir
s (but only to /
, you can't specify a path), does not touch umask
, and does not close the std*
descriptors (it optionally reopens them to /dev/null
though). (source)
So it depends on the platform, and at least one implementation does less than what you do. If you need all of what you're doing, stick with that (or stick to a platform where the daemon
function does exactly that).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With