创建守护程序时执行双叉的原因是什么? [英] What is the reason for performing a double fork when creating a daemon?

查看:59
本文介绍了创建守护程序时执行双叉的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python中创建一个守护进程。我发现了以下问题,它具有一些优点我目前正在关注其中的资源,但我很好奇为什么需要双叉。我到处搜寻Google,发现有很多资源声明有必要,但不是为什么。

I'm trying to create a daemon in python. I've found the following question, which has some good resources in it which I am currently following, but I'm curious as to why a double fork is necessary. I've scratched around google and found plenty of resources declaring that one is necessary, but not why.

有人提到这是为了防止守护程序获取控制终端。 。没有第二个分叉怎么办?有什么影响?

Some mention that it is to prevent the daemon from acquiring a controlling terminal. How would it do this without the second fork? What are the repercussions?

推荐答案

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

Looking at the code referenced in the question, the justification is:


分叉第二个孩子并立即退出以防僵尸。此
导致第二个子进程被孤立,使init
进程负责其清理。而且,由于第一个孩子是没有控制终端的会话领导者,因此将来有可能通过打开终端(基于系统V-
的系统)来获得
。第二个分叉确保孩子不再是
的会话领导者,从而防止守护程序获取
a控制终端。

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的任何可能性。因此,如果以上两种情况均不适用,那么一个叉子就足够了。 Unix网络编程-史蒂文斯有一个很好的部分

So it is to ensure that the daemon is re-parented onto init (just in case the process kicking off the daemon is long lived), and removes any chance of the daemon reacquiring a controlling tty. So if neither of these cases apply, then one fork should be sufficient. "Unix Network Programming - Stevens" has a good section on this.

这篇关于创建守护程序时执行双叉的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆