# Python程序Daemon化

python守护进程实现原理：

* 首先守护进程必须将自己与父进程分离开，所以在第一个 `os.fork()`操作完成后立即终结父进程
* 当子进程成为孤儿以后，就调用`os.setsid()`创建一个全新的进程会话，并将子进程设为会话的头领，也就是子进程设置为新的进程组的头领进程，并确保没有任何与之关联的控制终端。

## 参考

* [Python Cookbook：在UNIX上加载守护进程](https://www.amazon.cn/Python-Cookbook-%E4%B8%AD%E6%96%87%E7%89%88-%E7%BE%8E-%E5%A4%A7%E5%8D%AB%C2%B7%E6%AF%94%E6%96%AF%E5%88%A9-%E5%B8%83%E8%8E%B1%E6%81%A9%C2%B7K-%E7%90%BC%E6%96%AF-%E8%91%97/dp/B01N3T8KQS/ref=pd_sim_351_1?ie=UTF8\&psc=1\&refRID=Q3FTP4P4GWBXYVF96TWB)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://huataihuang.gitbook.io/cloud-atlas-draft/develop/python/startup/unix_daemonize.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
