Python中如何把程序放到后台执行

2023-01-31 02:01:20 执行 后台 放到

直接上代码:

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


相关文章