forked from geopy/geopy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.py
executable file
·89 lines (60 loc) · 1.88 KB
/
daemon.py
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#! /bin/env python
#
# Routine to daemonize a process on unix
#
#
DAEMON_HOME = '/'
class NullDevice(object):
def write(self, s):
pass
def daemonize(homeDir=DAEMON_HOME):
import os
import sys
if os.fork() != 0: # Parent
os._exit(0) # Kill parent
os.chdir(homeDir) # Detach from parent tty
os.setsid() # and start new session
os.umask(0)
sys.stdin.close() # Close stdin, stdout
sys.stdout.close()
sys.stdin = NullDevice()
sys.stdout = NullDevice()
for n in range(3, 256): # Close any remaining file
try: # descriptors
os.close(n)
except Exception:
pass
if os.fork() != 0: # finally fork again
os._exit(0) # to fully daemonize
def spawn(cmd, args):
import string
import os
import signal
# Prevent zombie orphans by ignoring SIGCHLD signal
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
args = string.split(args)
if os.fork() != 0: # Calling Parent
return # allow this parent to continue running
os.chdir(DAEMON_HOME) # Temp Parent
os.setsid() # Detach from calling parent
os.umask(0)
if os.fork() != 0: # Kill temp parent
os._exit(0) # Run cmd in new child
os.execvpe(cmd, [cmd] + args, os.environ)
def createPid(pidPath='/var/run'):
'''Creates PID file for process'''
import os
import sys
currentPid = os.getpid() # Gets PID number
if not currentPid:
print 'Could not find PID'
sys.exit()
scriptFilename, _ = os.path.splitext(os.path.basename(sys.argv[0]))
pidFile = '%s.pid' % (scriptFilename) # Creates PIDfile filename
pidFilePath = os.path.join(pidPath, pidFile)
with open(pidFilePath, 'w') as fileh: # Writes PIDfile name
fileh.write(currentPid)
if __name__ == "__main__":
while True:
daemonize()
print "hello world"