commit fcb73d038653ca19620620bfeddccc8802016325 Author: Sergiusz BazaƄski Date: Mon Apr 8 10:43:48 2013 +0200 Basic daemon code. diff --git a/bouncer.py b/bouncer.py new file mode 100644 index 0000000..4392765 --- /dev/null +++ b/bouncer.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python2 + +import os +import time +import sys +import subprocess + + +def doublefork(pidfile, logfile): + """Create a daemon process by double-forking, detaching standard streams and creating a pidfile.""" + def panic(message): + f = open(logfile, "aw") + f.write("panic: %s\n" % message) + f.close() + + try: + pid = os.fork() + except OSError as e: + panic("%s [%d]" % (e.strerror, e.errno)) + return False + + if pid == 0: + # we are the first child + os.setsid() + try: + pid = os.fork() + except OSError as e: + panic("%s [%d]" % (e.strerror, e.errno)) + return False + + if pid == 0: + # we are the second child + os.chdir("/") + os.umask(0) + else: + os._exit(0) + + else: + os._exit(0) + + pid = open(pidfile, "w") + pid.write("%i" % os.getpid()) + pid.close() + + stdout = os.open(logfile, os.O_CREAT | os.O_WRONLY | os.O_APPEND) + os.dup2(stdout, sys.stdout.fileno()) + os.dup2(stdout, sys.stderr.fileno()) + return True + +doublefork("/tmp/pid", "/tmp/log") +while True: + time.sleep(2) + print "cocks"