create python powered unix daemon

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/env python
#
# based on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731
import os, pwd, grp
def daemonize(euid = None, egid = None):
"""Detach a process from the controlling terminal,
change euid/egid and run it in the background as a daemon.
"""
try:
pid = os.fork()
except OSError, e:
raise Exception, "%s [%d]" % (e.strerror, e.errno)
if (pid == 0):
os.setsid()
try:
pid = os.fork()
except OSError, e:
raise Exception, "%s [%d]" % (e.strerror, e.errno)
if (pid == 0):
os.chdir('/')
os.umask(0)
else:
os._exit(0)
else:
os._exit(0)
for fd in range(0, 2):
os.close(fd)
os.open(os.devnull, os.O_RDONLY) # fd0 stdin
os.open(os.devnull, os.O_WRONLY) # fd1 sdtout
os.dup2(1, 2) # fd2 stderr
if euid:
os.seteuid(pwd.getpwnam(euid)[2])
if egid:
os.setegid(grp.getgrnam(egid)[2])