123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- #!/usr/bin/env python
- import sys, os, signal, subprocess, shlex,time,atexit
- shutdown = False
- queue_procs = None
- def file_pid(name):
- proc1 = subprocess.Popen(shlex.split('ps aux'), stdout=subprocess.PIPE)
- proc2 = subprocess.Popen(shlex.split('grep ' + name), stdin=proc1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- proc3 = subprocess.Popen(shlex.split('awk \'{print $2}\' '), stdin=proc2.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- proc1.stdout.close()
- proc2.stdout.close()
- out, err = proc3.communicate()
- lines = out.splitlines()
- pids = []
- for line in lines :
- item = line.strip()
- pid = int(item)
- if pid > 0:
- pids.append(pid)
- if len(pids) > 0 :
- return pids
- else:
- return []
- def kill_pid(name):
- print "start restart " + name
- cur_pid = os.getpid()
- pids = file_pid(name)
- for pid in pids:
- try:
- if cur_pid != pid:
- os.kill(pid, signal.SIGKILL)
- print 'kill pid=', pid
- else:
- continue
- except OSError, e:
- print "OSError no=", e.errno, " err=", e.strerror
- pass
- except BaseException, be:
- pass
- return
- def sig_handler(sig,frame):
- global shutdown
- global queue_procs
- frame = None
- if sig == signal.SIGINT:
- shutdown = True
- elif sig == signal.SIGTERM:
- shutdown = True
- if shutdown == True and queue_procs != None:
- for proc in queue_procs:
- proc.terminate()
- class Daemon(object):
- def __init__(self,stdin='/dev/null',stdout='/dev/null',stderr='/dev/null'):
- self.stdin = stdin
- self.stdout = stdout
- self.stderr = stderr
- def register_handler(self):
- signal.signal(signal.SIGINT, sig_handler)
- signal.signal(signal.SIGTERM, sig_handler)
- signal.signal(signal.SIGCHLD, sig_handler)
- def daemonize(self):
- try:
- pid = os.fork()
- if pid != 0:
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
- sys.exit(1)
- os.setsid()
- os.umask(0)
- try:
- pid = os.fork()
- if pid != 0:
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
- sys.exit(1)
- os.close(0)
- os.close(1)
- os.close(2)
- file(self.stdin, 'r')
- file(self.stdout, 'a+')
- file(self.stderr, 'a+')
- def main():
- global queue_procs
- kill_pid("qwatch.py")
- kill_pid("crontab.php")
- queue_procs = list()
- d = Daemon()
- d.daemonize()
- d.register_handler()
- while(shutdown == False):
- cmds = ["php", "./crontab.php", "queue", "index"]
- for i in range(0,10):
- subproc = subprocess.Popen(cmds,subprocess.PIPE)
- queue_procs.append(subproc)
- print "create queue porcess pid=",subproc.pid
- for proc in queue_procs:
- proc.wait()
- if __name__ == '__main__':
- main()
|