python产生守护进程的典型代码,两次fork,两次exit
1、代码示例:
import os import time def demo(): try: if os.fork() > 0: os._exit(0) except OSError, error: print 'fork #1 failed: %d (%s)' % (error.errno, error.strerror) os._exit(1) os.chdir('/') os.setsid() os.umask(0) try: if os.fork(): os._exit(0) except OSError, error: print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror) os._exit(1) test() def test(): f = open('/home/tomcat/py/log/demo.log', 'w') while True: f.write(time.ctime()+' ') f.flush() time.sleep(2) f.close() if __name__ == '__main__': demo()
2、解释: