I'm currently trying to manually create a simple daemon process, I don't want to use the existing externals libraries to avoid overhead.
I'm currently checking when my process runs that it doesn't have a PID file already created (meaning it's running), like described in this post.
I also have a daemonizing module to detach the PID from current process and redirect stdout and stderr (so my daemon will keep running even if I end my session):
import os
import sys
def daemonize(stdin="/dev/null", stdout="/dev/null", stderr="/dev/null"):
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write ("fork #1 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
os.chdir("/")
os.umask(0)
os.setsid()
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError, e:
sys.stderr.write ("fork #2 failed: (%d) %s\n" % (e.errno, e.strerror) )
sys.exit(1)
stdin_par = os.path.dirname(stdin)
stdout_par = os.path.dirname(stdout)
stderr_par = os.path.dirname(stderr)
if not stdin_par:
os.path.makedirs(stdin_par)
if not stdout_par:
os.path.makedirs(stdout_par)
if not stderr_par:
os.path.makedirs(stderr_par)
si = open(stdin, 'r')
so = open(stdout, 'a+')
se = open(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
So currently I can run my process like sample line below and it will run my daemon correctly:
>$ python myapp.py
But to stop it, I have to grep the PID (or take it from the lock file) and manually erase the PID after:
>$ ps -ef | grep myapp
xxxxx 11901 1 0 19:48 ? 00:00:00 python src/myapp.py
xxxxx 12282 7600 0 19:54 pts/7 00:00:00 grep myapp
>$ kill -9 11901
>$ rm -rf /path/to/lock.pid
I'd like to have a more Unix-like daemon where I can manage the daemon lifecycle with the following commands:
>$ python myapp.py start
>$ python myapp.py stop
>$ python myapp.py restart
I can certainly do it with the argparse
module, but that seems a bit tedious and ugly.
Do you know a simple and elegant solution to have a Unix-style daemon process in Python?
daemon
package: pypi.python.org/pypi/python-daemon – Blender Apr 18 '12 at 20:06