Linux: Difference between forking twice and daemon(ise)

前端 未结 2 1034
清歌不尽
清歌不尽 2021-01-20 13:44

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

相关标签:
2条回答
  • 2021-01-20 14:05

    There is a subtle difference.

    Forking twice: Intermediate child process can't become a zombie provided it has exited and has been waited for by Parent. Grandchild can't become a zombie either as it's parent (intermediate child process) has exited, so grandchild is an orphan. The orphan(grandchild) gets inherited by init and if it exits now, it is the responsibility of the system to clean it up. In this way, the parent process is releived of the responsibility of waiting to collect the exit status signal from child and also the parent can be busy doing some other work. This also enables the child to run for long time so that a shorttime parent need not wait for that amount of time.

    Daemon: This is for programs wishing to detach themselves from the controlling terminal and run in the background as system daemons. Has no controlling terminal.

    The decision of approach depends on the requirement/scenario in hand.

    0 讨论(0)
  • 2021-01-20 14:25

    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.

    0 讨论(0)
提交回复
热议问题