[英]Daemon in python generates defunct/zombie linux process
I'm trying to spawn long processes from a flask application. 我正在尝试从Flask应用程序中生成长进程。 So I have a main process that handles incoming web requests and from which I start daemons using the python-daemon library.
因此,我有一个主要流程来处理传入的Web请求,并使用python-daemon库从中启动守护程序。 Here is a minimal working example:
这是一个最小的工作示例:
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)
When I use the linux command ps -ef
while the main process is still running, after the daemon process has terminated, I see this output: 当主进程仍在运行时使用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>
The reason why I use the fork function before the with daemon_context:
statement is that I need the main process to continue. 我在
with daemon_context:
语句之前使用fork函数的原因是,我需要主进程才能继续。
Should I worry about the created defunct process (I might spawn a lot of them) ? 我是否应该担心已创建的已终止进程(我可能会产生很多)? How could I avoid this zombie to appear?
我如何避免这个僵尸出现?
If you don't want to create zombie processes you should wait for them to finish ie execute wait system call instead of sleep: 如果您不想创建僵尸进程,则应等待它们完成,即执行wait系统调用而不是sleep:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.