Skip to content

Instantly share code, notes, and snippets.

@fengsp
Created October 8, 2015 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fengsp/94dc524a857ae377ecc7 to your computer and use it in GitHub Desktop.
Save fengsp/94dc524a857ae377ecc7 to your computer and use it in GitHub Desktop.
A simple daemon in Python
"""
daemon
~~~~~~
A simple daemon.
:copyright: (c) 2015 by Shipeng Feng.
:license: BSD.
"""
import os
import sys
import atexit
class Daemon(object):
def __init__(self, pidfile):
self.pidfile = pidfile
def start(self):
"""Start the daemon."""
# Check pidfile
try:
pf = open(self.pidfile, 'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if pid is not None:
raise RuntimeError('pidfile %s already exist, does the daemon '
'already run with pid %s?' %
(self.pidfile, pid))
# Daemonize
if os.fork() > 0:
sys.exit(0)
os.setsid()
if os.fork() > 0:
sys.exit(0)
os.chdir('/')
os.umask(027)
sys.stdout.flush()
sys.stdout.flush()
devnull_fd = os.open('/dev/null', os.O_RDWR)
os.dup2(devnull_fd, 0)
os.dup2(devnull_fd, 1)
os.dup2(devnull_fd, 2)
atexit.register(lambda: os.remove(self.pidfile))
pf = open(self.pidfile, 'w')
pf.write('%s' % os.getpid())
pf.close()
self.run()
def run(self):
raise NotImplementedError('write your logic here')
if __name__ == '__main__':
class DaemonExample(Daemon):
def run(self):
import time
for i in range(4):
time.sleep(5)
daemon = DaemonExample('/tmp/daemon_example.pid')
daemon.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment