daemon进程
守护进程
1.fork子进程,而后父进程退出,此时子进程会被init进程接管
2.修改子进程的工作目录,创建新进程组和新会话,修改umask
3.子进程再次fork一个进程,这个进程可以称为孙子进程,而后子进程退出
4.重定向孙子进程标准输入流,标准输出等
atexit程序退出 调用某个函数
kill 级别
#!/usr/bin/env python import time import os import sys import atexit import signal def run(): while True: print "1time" time.sleep(1) print os.getpid() def writeData(signum, frame): with open('/tmp/data.txt', 'a+') as fd: fd.write('abcd\n') def writePid(name, pid): pidpath = os.path.join('/tmp','%s.pid' % name) with open(pidpath, 'w') as fd: fd.write(str(pid)) def delPid(name): pidpath = os.path.join('/tmp','%s.pid' % name) os.remove(pidpath) def term(signum, frame): raise SystemExit(u'terminated by %(signum)r' % vars()) def daemon(name): try: pid = os.fork() if pid > 0: print "1st pid", pid sys.exit(0) except OSError, e: print e sys.exit(1) os.chdir('/') os.setsid() os.setgid(99) os.setuid(99) os.umask(0) try: pid = os.fork() if pid > 0: writePid(name,pid) print "2nd pid", pid sys.exit(0) except OSError, e: print e sys.exit(1) stdin = file('/dev/null', 'r') stdout = file('/dev/null', 'w') stderr = file('/dev/null', 'w',0) os.dup2(stdin.fileno(), sys.stdin.fileno()) os.dup2(stdout.fileno(), sys.stdout.fileno()) os.dup2(stderr.fileno(), sys.stderr.fileno()) atexit.register(delPid, name=name) signal.signal(signal.SIGTERM, term) signal.signal(signal.SIGHUP, writeData) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-d': daemon('example-daemon') run()
本文出自 “muzinan的技术博客” 博客,谢绝转载!