I was trying to write a basic multiprocessing tcp-server, which forks a process for every new accept().
I don\'t need the parent process to wait on the child process
You do need the parent process to (eventually) wait()
for each of its child processes, else the children will hang around until the parent exits. This is a form of resource leak.
Forking twice, with the intermediate process exiting immediately after forking, allows the original process to collect the child immediately (via wait()
), and makes the grandchild process an orphan, which the system has responsibility for cleaning up. This is one way to avoid accumulating zombie processes. The grandchild remains in the same process group (and thus the same session) as the original process.
Daemonizing serves a somewhat different purpose. It puts the resulting (child) process in a new session (and new process group) with no controlling terminal. The same effect can be achieved by forking once, with the parent immediately calling _exit()
and the child calling setsid()
.
A system service daemonizes to escape the session in which it was launched, so as not to be shut down when that session ends. This has little to do with multiprocessing, but a lot to do with process management. A process double-forks to avoid process management duties for the (grand)child processes; this has both multiprocessing and process management aspects.
Note, too, that double-forking doesn't just pass off process-management responsibilty, it also gives up process-management ability. Whether that's a good trade-off is situation-dependent.