python - 关闭 Python 守护进程时运行代码

标签 python linux daemon python-daemon

我正在使用著名的code referenced herehere在 Python 中做一个守护进程,如下所示:

import sys, daemon

class test(daemon.Daemon):
    def run(self):
        self.db = somedb.connect()            # connect to a DB
        self.blah = 127
        with open('blah0.txt', 'w') as f:
            f.write(self.blah)
        # doing lots of things here, modifying self.blah

    def before_stop(self):
        self.db.close()                      # properly close the DB (sync to disk, etc.)
        with open('blah1.txt', 'w') as f:
            f.write(self.blah)

daemon = test(pidfile='_.pid')

if 'start' == sys.argv[1]: 
    daemon.start()
elif 'stop' == sys.argv[1]: 
    daemon.before_stop()               # AttributeError: test instance has no attribute 'blah'
    daemon.stop()

问题是,当调用 ./myscript.py stop 以及 daemon.before_stop() 时,不再引用 self.blah!

AttributeError: test instance has no attribute 'blah'

因此,使用这种守护进程化方法,在停止守护进程之前不可能访问守护进程的变量...

问题:如何访问之前的守护程序类变量:

  • 使用 ./myscript.py stop 停止

  • 被 SIGTERM 停止

  • (被杀?)


编辑:已解决,并且 here is a working daemon code with a quit() method.

最佳答案

守护进程代码向守护进程进程发送 SIGTERM 信号,要求其停止。如果您希望某些东西由守护进程本身运行,则必须从信号处理程序或atexit.register 调用的方法运行。

daemonize 方法已经安装了这样的方法,只需从那里调用 beforestop 即可:

# this one could be either in a subclass or in a modified base daemeon class
def delpid(self):
        if hasattr(self, 'before_stop'):
                self.before_stop()
        os.remove(self.pidfile)

# this one should be in subclass
def before_stop(self):
    self.db.close()                      # properly close the DB (sync to disk, etc.)
    with open('blah1.txt', 'w') as f:
        f.write(self.blah)

但这还不够! Python 标准库文档介绍了 atexit:

The functions registered via this module are not called when the program is killed by a signal not handled by Python

由于进程预计会收到 SIGTERM 信号,因此您必须安装处理程序。如一active state recipe ,这非常简单:只要让程序在收到信号时停止即可:

...
from signal import signal, SIGTERM
...

atexit.register(self.delpid)
signal(SIGTERM, lambda signum, stack_frame: exit(1))

关于python - 关闭 Python 守护进程时运行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40391812/

相关文章:

python - 以太网 CRC32 计算 - 软件与算法结果

python - x 刻度和标签的自定义定位

python - IOError - 解码器 jpeg 不可用 - 即使在安装 libjpeg-dev n PIL 之后也是如此

ruby-on-rails - 在 Ruby on Rails 中使用服务器停止守护进程

java - 由于文件锁定超时,Gradle 守护进程停止并行工作

FreeBSD 的守护进程库

python - 使用 python bash float 数学

ruby-on-rails - rvm环境负载

linux - 如何使用 awk 显示文本文件中的重复项

linux - 删除名称中带连字符的目录