Double fork
- personal
- finished
Roughly 4 years ago we learned about fork() function. Sometimes when we want the process to become a daemon, i.e. to run in background by detaching from a controlling terminal without a possibility to reattach, it’s useful to perform a technique known as double fork.
The steps are:
- the parent forks to create the child and exits;
- the child becomes a new session leader by calling
setsid()
; - the child calls
fork()
again and exits.
Creating a new session during step 2 detaches child from parent’s TTY, but now as a session leader, the process could acquire TTY (accidentally or intentionally), which is unwanted for daemons. To prevent that, second fork (a grandchild) is created, which is not a session leader and thus cannot acquire a terminal.
So strictly speaking I forked twice and not double forked (maybe I will one day), but also strictly speaking I am not a UNIX environment.