How do I manage a Python based daemon on Linux?
On linux there is a start-stop-daemon utility as part of the init.d tools.
It is very flexible and allows different ways for capturing the pid of your server.
There is also a file /etc/init.d/skeleton which can serve as a basis for your own init.d script.
If your target platform is debian based, it makes sense to create a debina package to deploy it as it also helps getting a daemon properly integrated in the rest of the system. And it is not too complicated (if you have done it ten times before ;-)
If you want to do it with code in python, this is a pretty standard C-method that was ported to python that I use. It works flawlessly, and you can even choose a file output.
import osimport signaldef daemonize(workingdir='.', umask=0,outfile='/dev/null'):#Put in backgroundpid = os.fork()if pid == 0: #First child os.setsid() pid = os.fork() #fork again if pid == 0: os.chdir(workingdir) os.umask(umask) else: os._exit(0)else: os._exit(0)#Close all open resourcestry: os.close(0) os.close(1) os.close(2)except: raise Exception("Unable to close standard output. Try running with 'nodaemon'") os._exit(1)#Redirect outputos.open(outfile, os.O_RDWR | os.O_CREAT)os.dup2(0,1)os.dup2(0,2)
Then, you can use signals to catch when a kill-signal was sent to the program and exit nicely. Example from Python Docs
import signal, osdef handler(signum, frame): print 'Signal handler called with signal', signum raise IOError("Couldn't open device!")# Set the signal handler and a 5-second alarmsignal.signal(signal.SIGALRM, handler)signal.alarm(5)# This open() may hang indefinitelyfd = os.open('/dev/ttyS0', os.O_RDWR)signal.alarm(0) # Disable the alarm