I'm using the famous code referenced here or here to do a daemon in Python, like this:
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()
The problem is that when calling ./myscript.py stop
and thus daemon.before_stop()
, there is no reference anymore to self.blah
!
AttributeError: test instance has no attribute 'blah'
Thus with this daemonization method, it's impossible to have access to the daemon's variables before stopping the daemon...
Question: how to have access to the daemon class' variables just before:
stopping with
./myscript.py stop
being stopped with SIGTERM
(being killed?)
EDIT: solved, and here is a working daemon code with a quit()
method.