Daemons double-fork
For those who were not aware (and hopefully are now by the title) almost every Linux / Unix service that daemonizes does so by using a double-fork technique. This means that the application performs the following:- The application (parent) forks a child process
- The parent process terminates
- The child forks a grandchild process
- The child process terminates
- The grandchild process is now the daemon
The technical reason
First I'll give the technical documented reason for this and then I'll break this down into something a bit more consumable. POSIX.1-2008 Section 11.1.3, "The Controlling Terminal" states the following:
The controlling terminal for a session is allocated by the session leader in an implementation-defined manner. If a session leader has no controlling terminal, and opens a terminal device file that is not already associated with a session without using the O_NOCTTY option (see open()), it is implementation-defined whether the terminal becomes the controlling terminal of the session leader. If a process which is not a session leader opens a terminal file, or the O_NOCTTY option is used on open(), then that terminal shall not become the controlling terminal of the calling process.
The breakdown
When you fork and kill the parent of the fork the new child will become a child of "init" (the main process of the system, given a PID of 1). You may find others state on the interweb that the double-fork is needed for this to happen, but that isn't true, a single fork will do this.
What we are actually doing is a kind of safety thing to make sure that the daemon is completely detached from the terminal. The real steps behind the double-fork are as follows:
- The parent forks the child
- The parent exits
- The child calls setsid() to start a new session with no controlling terminals
- The child forks a grandchild
- The child exits
- The grandchild is now the daemon
Put simply it is a roundabout way of completely detaching itself from the terminal that started the daemon. It isn't a strict requirement to do this at all, many modern init systems can daemonize a process that will stay in the foreground quite easily. But it is useful for systems that can't do this and for anything that at some point in time is expected to be run without an init script.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.