在创建守护进程时执行两次fork原因是什么?

问题:

我试图在python中创建一个守护进程。我找到了following question,它有一些很好的资源,我正在关注,但我很好奇为什么两次fork是必要的。我已经在google上找到了大量的资源,宣称有必要,但不是为什么。
有人提到这是为了防止守护进程获取控制终端。没有第二个叉子怎么办?有什么影响?

回答:

看看问题引用的代码,理由是:

# Fork a second child and exit immediately to prevent zombies.  This
# causes the second child process to be orphaned, making the init
# process responsible for its cleanup.  And, since the first child is
# a session leader without a controlling terminal, it's possible for
# it to acquire one by opening a terminal in the future (System V-
# based systems).  This second fork guarantees that the child is no
# longer a session leader, preventing the daemon from ever acquiring
# a controlling terminal.

所以这样做是为了确保将守护进程重新加载到init上(以防止进程启动守护进程长时间存在),并且可以消除守护程序重新获取控制tty的机会。所以如果这两种情况都不适用,那么一个fork就足够了。 “Unix Network Programming – Stevens”有一个很好的部分。

Code问答: http://codewenda.com/topics/python/
Stackoverflow: What is the reason for performing a double fork when creating a daemon?

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

+ 19 = 24