且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么而fork()的两次daemonizing?

更新时间:2023-12-04 12:18:28

第一次调用叉(2)确保过程不是组长,使它有可能为这一进程创造一个新的会话,成为会话组长。还有其他原因,第一个叉(2):如果守护进程开始作为一个shell命令,具有过程叉和家长退出使得外壳回到它的提示并等待更多的命令。

The first call to fork(2) ensures that the process is not a group leader, so that it is possible for that process to create a new session and become a session leader. There are other reasons for the first fork(2): if the daemon was started as a shell command, having the process fork and the parent exit makes the shell go back to its prompt and wait for more commands.

第二个叉(2)是有保证新进程不是会话组长,所以它不能够(不小心)分配一个控制终端,因为守护进程不应该曾经有一个控制终端。关于第二个岔路口,这里是从的 UNIX环境的第13章(守护进程)高级编程报价:

The second fork(2) is there to ensure that the new process is not a session leader, so it won't be able to (accidentally) allocate a controlling terminal, since daemons are not supposed to ever have a controlling terminal. About the 2nd fork, here's a quote from Advanced Programming in the UNIX Environment, Chapter 13 (Daemon Processes):

在基于System V的系统中,有些人建议再次调用fork
  在这点上,终止母体,并继续在后台
  这个孩子。这保证了守护进程不是会话组长,
  从下获取控制终端其中prevents它
  System V的规则。另外,为了避免收购控股
  终端,一定要指定O_NOCTTY只要打开终端
  设备。

Under System V-based systems, some people recommend calling fork again at this point, terminating the parent, and continuing the daemon in the child. This guarantees that the daemon is not a session leader, which prevents it from acquiring a controlling terminal under the System V rules. Alternatively, to avoid acquiring a controlling terminal, be sure to specify O_NOCTTY whenever opening a terminal device.

这本书的第13.3节描述了daemonizing的过程时使用了更多的规则和模式,这是非常值得的时间去阅读它,如果你能。

Section 13.3 of that book describes a lot more rules and patterns that are used when daemonizing a process, it is well worth the time to read it, if you can.