Linux: Difference between forking twice and daemon

2020-04-11 09:40发布

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 processes. I have come across two solutions- forking twice and daemonising.

  1. What's the difference between the two?
  2. Which is more suitable in this scenario?
  3. What are the factors that are to be kept in mind for choosing one amongst these?

2条回答
太酷不给撩
2楼-- · 2020-04-11 10:11

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.

查看更多
可以哭但决不认输i
3楼-- · 2020-04-11 10:14

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.

查看更多
登录 后发表回答