3 import sys, os, time, atexit
4 from signal import SIGTERM
8 A generic daemon class.
10 Usage: subclass the Daemon class and override the run() method
12 def __init__(self, pidfile, stdin='/dev/null', stdout='/tmp/plab', stderr='/tmp/plab.err'):
16 self.pidfile = pidfile
20 do the UNIX double-fork magic, see Stevens' "Advanced
21 Programming in the UNIX Environment" for details (ISBN 0201563177)
22 http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
30 sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
33 # decouple from parent environment
34 os.chdir("/var/www/lib/cgi/")
42 # exit from second parent
45 sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
48 # redirect standard file descriptors
51 si = file(self.stdin, 'r')
52 so = file(self.stdout, 'a+')
53 se = file(self.stderr, 'a+', 0)
54 os.dup2(si.fileno(), sys.stdin.fileno())
55 os.dup2(so.fileno(), sys.stdout.fileno())
56 os.dup2(se.fileno(), sys.stderr.fileno())
59 atexit.register(self.delpid)
60 pid = str(os.getpid())
61 file(self.pidfile,'w+').write("%s\n" % pid)
64 os.remove(self.pidfile)
70 # Check for a pidfile to see if the daemon already runs
72 pf = file(self.pidfile,'r')
73 pid = int(pf.read().strip())
79 message = "pidfile %s already exist. Daemon already running?\n"
80 sys.stderr.write(message % self.pidfile)
91 # Get the pid from the pidfile
93 pf = file(self.pidfile,'r')
94 pid = int(pf.read().strip())
100 message = "pidfile %s does not exist. Daemon not running?\n"
101 sys.stderr.write(message % self.pidfile)
102 return # not an error in a restart
104 # Try killing the daemon process
107 os.kill(pid, SIGTERM)
111 if err.find("No such process") > 0:
112 if os.path.exists(self.pidfile):
113 os.remove(self.pidfile)
127 You should override this method when you subclass Daemon. It will be called after the process has been
128 daemonized by start() or restart().