Novell Home

Writing Daemons

From Developer Community

Acknowledgement

Much of the content from this article is paraphrased from W. Richard Stevens excellent work, "Advanced Programming in the UNIX Environment" (ISBN 0201563177).

About Daemons

A daemon is a special type of process that has a few key characteristics:

  • Long Life - A daemon is intended to run for a long time. This isn't the same thing as an application that might run for a long time, like performing an MD5 sum on a 500 gigabyte file. Daemons are applications that live for a long time, usually in a dormant state, and periodically receive work to do.
  • System-Oriented - We say that daemons are system-oriented because most daemons start life at system bootup and live until the system is shut down, although this is not necessary for a process to be a daemon. Most of the services that you expect on a Linux system (such as system logging, cron, deleted file removal) run as daemons.
  • Background Execution - A daemon runs as a background process. It does not have a controlling terminal.

Applications that are Daemons

W. Richard Stevens tells us that applications that need to be daemons should take a few things into consideration in order for the running application to assume the characteristics of a daemon process.

  1. fork() and have the parent exit() - this causes the control to return to the shell, among other things.
  2. setsid() to create a new session.
  3. Change the working directory to root (or, under some circumstances, to another location for a specific reason).
  4. Set file mode creation mask to 0.


As far as I am concerned, if Richard Stevens says to do it, that is good enough reason for me to do it.


I'd propose that well-behaved daemons should do a few additional things:

  • They should log all of their messages to the system logging facility.
  • They should be equipped to handle signals sent by the system. In particular, they should:
    • Reload their configuration files when they receive SIGHUP
    • Gracefully shut down when they receive SIGTERM
  • They usually have to read in configuration to know how they should be executing.


As this article continues to be enhanced, I'll give some examples of code that show how to accomplish these tasks in simple applications.


See Also: Multiprocess Linux Applications

Novell® Making IT Work As One

© 2009 Novell, Inc. All Rights Reserved.