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

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

问题描述

我正在尝试在 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:

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

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 网络编程 - Stevens" 有一个很好的部分

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天全站免登陆