Why use os.setsid() in Python?

痴心易碎 提交于 2019-12-04 15:27:05

Calling setsid is usually one of the steps a process goes through when becoming a so called daemon process. (We are talking about Linux/Unix OS).

With setsid the association with the controlling terminal breaks. This means that the process will be NOT affected by a logout.

There are other way how to survive a logout, but the purpose of this 'daemonizing' process is to create a background process as independent from the outside world as possible.

That's why all inherited descriptors are closed; cwd is set to an appropriate directory, often the root directory; and the process leaves the session it was started from.

A double fork approach is generally recommended. At each fork the parent exits and the child continues. Actually nothing changes except the PID, but that's exactly what is needed here.

First fork before the setsid makes sure the process is not a process group leader. That is required for a succesfull setsid.

The second fork after the setsid makes sure that a new association with a controlling terminal won't be started merely by opening a terminal device.


NOTE: when a daemon process is started from systemd, the systemd can arrange everything described above so the process does not have to.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!