4

There are a lot of example implementations of daemons on the net. Most that I saw do not use the daemon(3) function to run the program in the background. Is that just a matter of taste, ignorance, or is there a good reason to write my own daemonize function? Is there a specific disadvantage in using daemon(3)? Is it insecure?

Jan Deinhard
  • 19,645
  • 24
  • 81
  • 137

4 Answers4

5

The daemon() function was not historically available in all flavors of Unix, so a lot of "portable" code doesn't use it. There's really no reason to roll your own recipe as long as all the target platforms you care about have daemon().

Kaelin Colclasure
  • 3,925
  • 1
  • 26
  • 36
3

The BSD daemon() function is very limited and invites misuse. Only very few daemons may use this function correctly.

The systemd man pages have a list of what a correctly written SysV daemon should do when daemonizing:

http://0pointer.de/public/systemd-man/daemon.html

user175104
  • 3,598
  • 2
  • 23
  • 20
3

There is no daemon function in POSIX. It's a vendor extension. Thus anyone writing portable code simply writes their own.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
2

If you don't like any of the standard daemon() function actions, you might write your own. You can control whether it switches to the root directory; you can control whether it reconnects the standard I/O channels to /dev/null. But if you want to keep stderr open to a log file, while reconnecting stdin and stdout to /dev/null, you have to decide whether to use daemon() with appropriate options followed by other code is better than rolling your own.

There isn't much rocket science in daemon(); it calls fork() and setsid() (according to the Linux version; the MacOS version mentions suspending SIGHUP while daemon() is operating). Check out the standard resources for more information on daemonization — for example:

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278