且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从python运行程序,并在脚本被杀死后继续运行

更新时间:2023-12-05 19:21:28

在 Unix 系统上执行此操作的通常方法是,如果您是父级,则分叉并退出.看看 os.fork() .

The usual way to do this on Unix systems is to fork and exit if you're the parent. Have a look at os.fork() .

这是一个完成这项工作的函数:

Here's a function that does the job:

def spawnDaemon(func):
    # do the UNIX double-fork magic, see Stevens' "Advanced 
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try: 
        pid = os.fork() 
        if pid > 0:
            # parent process, return and keep running
            return
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) 
        sys.exit(1)

    os.setsid()

    # do second fork
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit from second parent
            sys.exit(0) 
    except OSError, e: 
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) 
        sys.exit(1)

    # do stuff
    func()

    # all done
    os._exit(os.EX_OK)