The first call to fork(2)
ensures that the process is not a group leader, so that it is possible for that process to create a new session and become a session leader. There are other reasons for the first fork(2)
: if the daemon was started as a shell command, having the process fork and the parent exit makes the shell go back to its prompt and wait for more commands.
The second fork(2)
is there to ensure that the new process is not a session leader, so it won't be able to (accidentally) allocate a controlling terminal, since daemons are not supposed to ever have a controlling terminal. About the 2nd fork, here's a quote from Advanced Programming in the UNIX Environment, Chapter 13 (Daemon Processes):
Under System V-based systems, some people recommend calling fork again
at this point, terminating the parent, and continuing the daemon in
the child. This guarantees that the daemon is not a session leader,
which prevents it from acquiring a controlling terminal under the
System V rules. Alternatively, to avoid acquiring a controlling
terminal, be sure to specify O_NOCTTY whenever opening a terminal
device.
Section 13.3 of that book describes a lot more rules and patterns that are used when daemonizing a process, it is well worth the time to read it, if you can.