[Python]第五课笔记 --多进程及守护进程编写
#coding=utf8#python2.7 参考cookbookimport os,sysdef guardtest(stdin='/dev/null',stdout='/dev/null',stderr='/dev/null'): #首次fork try: pid = os.fork() if pid>0: sys.exit(0) except IOError,e: e.message sys.exit(1) #从母体分离 os.chdir('/') os.setsid() os.umask(0) #第二次fork try: pid = os.fork() if pid>0: sys.exit(0) except OSError,e: sys.exit(1) #完成守护了 for f in sys.stdout,sys.stderr: f.flush() si = file(stdin,'r') so = file(stdout,'a+') se = file(stderr,'a+',0) os.dup2(si.fileno(),sys.stdin.fileno()) os.dup2(so.fileno(),sys.stdout.fileno()) os.dup2(se.fileno(),sys.stderr.fileno()) def mains(): import time sys.stdout.write('the input sid is %d'%os.getpid()) sys.stdout.write('output wirtor') sys.stderr.write('err wirtor') c = 0 for i in range(100): sys.stdout.write('No %d and time is %s \n'%(c,time.ctime())) sys.stdout.flush() c+=1if __name__=='__main__': guardtest('/dev/null','/tmp/deamon.log','/tmp/deamon.log') mains()