【问题标题】:Daemon in python generates defunct/zombie linux processpython中的守护进程生成defunct/zombie linux进程
【发布时间】:2019-08-03 02:29:54
【问题描述】:

我正在尝试从烧瓶应用程序中生成长进程。因此,我有一个处理传入 Web 请求的主进程,并从该进程中使用 python-daemon 库启动守护进程。这是一个最小的工作示例:

import os
import time
import daemon
import lockfile

def daemon_function():
    return True

working_directory = os.path.dirname(os.path.abspath(__file__))
pid_file = os.path.join(working_directory,"my_daemon.pid")

daemon_context = daemon.DaemonContext(
        working_directory=working_directory,
        pidfile=lockfile.FileLock(pid_file),
    )

pid = os.fork()
if pid == 0:
    with daemon_context:
        daemon_function()

time.sleep(10)

当我在主进程仍在运行时使用 linux 命令ps -ef 时,在守护进程终止后,我看到以下输出:

user     2484     1  0 09:38 ?        00:00:01 /lib/systemd/systemd --user
user    11269  6061  0 12:07 pts/2    00:00:00 bash
user    28817 11269  1 15:43 pts/2    00:00:00 python test_daemon.py
user    28818 28817  0 15:43 pts/2    00:00:00 [python] <defunct>

我之所以在with daemon_context:语句之前使用fork函数是因为我需要主进程继续。

我应该担心创建的失效进程(我可能会产生很多)吗?怎么才能避免这个丧尸出现?

【问题讨论】:

    标签: python daemon zombie-process python-daemon defunct


    【解决方案1】:

    如果您不想创建僵尸进程,您应该等待它们完成,即执行等待系统调用而不是睡眠:

    import os
    import time
    import daemon
    import lockfile
    
    def daemon_function():
        return True
    
    working_directory = os.path.dirname(os.path.abspath(__file__))
    pid_file = os.path.join(working_directory,"my_daemon.pid")
    
    daemon_context = daemon.DaemonContext(
            working_directory=working_directory,
            pidfile=lockfile.FileLock(pid_file),
        )
    
    pid = os.fork()
    if pid == 0:
        with daemon_context:
            daemon_function()
    
    os.waitpid(pid, 0)
    

    【讨论】:

    • 嗯嗯,这比我预期的要容易:-)。你实际上可以让最后一行 time.sleep(10) 结束,它代表某种无限循环。由于父 pid 不做任何事情,最后一个 os.waitpid(pid, 0) 立即到达。谢谢
    猜你喜欢
    • 2018-06-07
    • 2011-03-06
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多