2 import sys, os, time, atexit
4 from signal import SIGTERM
6 LOG = logging.getLogger(__name__)
11 A generic daemon class.
13 Usage: subclass the Daemon class and override the run() method
15 def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
16 super(Daemon, self).__init__()
20 self.pidfile = pidfile
24 do the UNIX double-fork magic, see Stevens' "Advanced
25 Programming in the UNIX Environment" for details (ISBN 0201563177)
26 http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
33 LOG.error("fork #1 failed: %(errno)s, %(strerror)s",
34 {'errno':e.errno, 'strerror': e.strerror})
37 # decouple from parent environment
46 # exit from second parent
49 LOG.error("fork #1 failed: %(errno)s, %(strerror)s",
50 {'errno':e.errno, 'strerror': e.strerror})
53 # redirect standard file descriptors
56 si = file(self.stdin, 'r')
57 so = file(self.stdout, 'a+')
58 se = file(self.stderr, 'a+', 0)
59 os.dup2(si.fileno(), sys.stdin.fileno())
60 os.dup2(so.fileno(), sys.stdout.fileno())
61 os.dup2(se.fileno(), sys.stderr.fileno())
64 atexit.register(self.delpid)
65 pid = str(os.getpid())
66 file(self.pidfile,'w+').write("%s\n" % pid)
69 os.remove(self.pidfile)
76 # Check for a pidfile to see if the daemon already runs
78 pf = file(self.pidfile,'r')
79 pid = int(pf.read().strip())
85 message = "pidfile %s already exist. Daemon already running?\n"
86 sys.stderr.write(message % self.pidfile)
88 LOG.info("daemon start to run daemonize")
97 # Get the pid from the pidfile
99 pf = file(self.pidfile,'r')
100 pid = int(pf.read().strip())
106 message = "pidfile %s does not exist. Daemon not running?\n"
107 sys.stderr.write(message % self.pidfile)
108 return # not an error in a restart
110 # Try killing the daemon process
113 os.kill(pid, SIGTERM)
117 if err.find("No such process") > 0:
118 if os.path.exists(self.pidfile):
119 os.remove(self.pidfile)
133 You should override this method when you subclass Daemon.
134 It will be called after the process has been
135 daemonized by start() or restart().
140 def daemon_die(self):
141 """You should this method when you shutdown daemon
142 this func will be call by stop() before kill the process