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()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章