blob: edb8bc40e831902e69691dbcc865469f3734cfa7 (
plain)
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
37
38
39
40
41
42
43
44
|
'''Bcfg2 daemon support'''
__revision__ = '$Revision$'
import os, sys
def daemonize(filename):
'''Do the double fork/setsession dance'''
# Check if the pid is active
try:
pidfile = open(filename, "r")
oldpid = int(pidfile.readline())
# getpgid() will retun an IO error if all fails
os.getpgid(oldpid)
pidfile.close()
# If we got this far without exceptions, there is another instance
# running. Exit gracefully.
print "PID File (%s) exists and listed PID (%d) is active." % \
(filename, oldpid)
raise SystemExit, 1
except OSError:
pidfile.close()
except IOError:
# pid file doesn't
pass
# Fork once
if os.fork() != 0:
os._exit(0)
os.setsid() # Create new session
pid = os.fork()
if pid != 0:
pidfile = open(filename, "w")
pidfile.write("%i" % pid)
pidfile.close()
os._exit(0)
os.chdir("/")
os.umask(0)
null = open("/dev/null", "w+")
os.dup2(null.fileno(), sys.__stdin__.fileno())
os.dup2(null.fileno(), sys.__stdout__.fileno())
os.dup2(null.fileno(), sys.__stderr__.fileno())
|