#!/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)