我正在使用著名的code referenced here或here在 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/