Python中如何把程式放到後台執行
直接上程式碼: [root@MGServer pythonscript]# cat getio.py #!/usr/bin/env python #encoding:utf8 import sys,time,os,platform #定義我自己要在後台運行的程式 def getio(): while True: os.system("/usr/sbin/iotop -n 2 -b -o -k >>/root/iotop.log") time.sleep(10) #fork後台運行進程 def createDaemon(): # fork進程 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: pid = os.fork() if pid > 0: print 'Daemon PID %d' % pid os._exit(0) except OSError, error: print 'fork #2 failed: %d (%s)' % (error.errno, error.strerror) os._exit(0) # 重定向標準IO sys.stdout.flush() sys.stderr.flush() si = file("/dev/null", 'r') so = file("/dev/null", 'a+') se = file("/dev/null", 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # 在子進程中執行程式碼 getio() #執行函數createDaemon createDaemon()