Double fork

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:

  1. the parent forks to create the child and exits;
  2. the child becomes a new session leader by calling setsid();
  3. 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.

Ultrasound photo

We are the fork. Lower your shields and surrender your ships. We will add your biological and technological distinctiveness to our own. Your culture will adapt to service us. Resistance is futile.