fork zlo

  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
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#!/usr/local/bin/python
import os, sys
import signal
import inspect
import threading
import timeit
import stat
from time import sleep
import time
LOGFILE='log.txt'
CHILDPID='mychildspids'
thrn = 0
class Log:
def __init__(self, f):
self.f = f
def write(self, s):
self.f.write(s)
self.f.flush()
def sig_handler(*args, **kwargs):
if len(args) > 0 and inspect.isfunction(args[0]):
usr_handler = args[0]
args = args[1:]
def res_handler(sing_num, frame):
usr_handler(*args, **kwargs)
return res_handler
else:
def tmp_handler(handler_func):
return sig_handler(handler_func, *args, **kwargs)
return tmp_handler
def child_pidfile(pidfile):
@sig_handler(pidfile)
def child_delete_pidfile(pidfile):
print "child sigterm arrived"
d = open(pidfile, 'r')
lines = d.readlines()
lines = map(str,lines)
lines = map(str.rstrip,lines)
mypid = str(os.getpid())
if mypid in lines:
print "ya ya im child"
del lines[lines.index(mypid)]
d.write("\n".join(lines))
else:
print "hm.. huy"
d.close
if len(lines) == 0:
os.unlink(pidfile)
os._exit(0)
try:
mode = os.stat(pidfile)
except OSError, e:
fm = 'w'
else:
if mode[stat.ST_SIZE] > 0:
fm='a'
open(pidfile, fm).write(str(os.getpid())+"\n")
signal.signal(signal.SIGTERM, child_delete_pidfile)
def create_masterpid(pidfile):
@sig_handler(pidfile)
def master_delete_pidfile(pidfile):
print "master sigterm arrived"
d = open(pidfile, 'r')
lines = d.readlines()
lines = map(str.rstrip,lines)
lines = map(int,lines)
d.close
for line in lines:
print "master is killing %s" % line
os.kill(line, signal.SIGTERM)
os.unlink(pidfile)
sys.exit(0)
open(pidfile, 'w').write(str(os.getpid()))
signal.signal(signal.SIGTERM, master_delete_pidfile)
def main(params):
while 1:
sleep(0.5)
if __name__ == '__main__':
if os.fork() != 0:
os._exit(0)
os.setsid()
if os.fork() != 0:
os._exit(0)
#else:
#sys.exit(1)
sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))
for i in range(1,5):
print "trying to create %i daemon" % i
pid = os.fork()
if pid > 0:
print "deamon %i online!" % pid
child_pidfile(CHILDPID)
main(i)
os._exit(0)
master = os.getpid()
print "heey, im master! %i" % master
create_masterpid("master.pid")
while 1:
sleep(0.5)
sys.exit(0)