python - 故意在python中制作一个孤儿进程

我有一个名为 MyScript 的 python 脚本(类 unix,基于 RHEL),它有两个函数,分别称为 A 和 B。我希望它们在不同的独立进程中运行(分离 B 和 A):

  • 启动脚本 MyScript
  • 执行函数A
  • 生成一个新进程,将数据从函数 A 传递到 B
  • 当函数 B 运行时,继续执行函数 A
  • 当函数 A 完成时,退出 MyScript,即使 B 仍在运行

我想我应该使用 multiprocessing 来创建一个守护进程,但是 documentation表明这不是正确的用例。所以,我决定生成一个子进程和 child^2 进程( child 的 child ),然后强制 child 终止。虽然此变通方法似乎有效,但看起来真的很难看。

你能帮我让它更像 pythonic 吗? subprocess 模块是否有一个可以对函数进行操作的方法?下面的示例代码。

import multiprocessing
import time
import sys
import os

def parent_child():
    p = multiprocessing.current_process()
    print 'Starting parent child:', p.name, p.pid
    sys.stdout.flush()
    cc = multiprocessing.Process(name='childchild', target=child_child)
    cc.daemon = False
    cc.start()
    print 'Exiting parent child:', p.name, p.pid
    sys.stdout.flush()

def child_child():
    p = multiprocessing.current_process()
    print 'Starting child child:', p.name, p.pid
    sys.stdout.flush()
    time.sleep(30)
    print 'Exiting child child:', p.name, p.pid
    sys.stdout.flush()

def main():
    print 'starting main', os.getpid()
    d = multiprocessing.Process(name='parentchild', target=parent_child)
    d.daemon = False
    d.start()
    time.sleep(5)
    d.terminate()
    print 'exiting main', os.getpid()

main()

最佳答案

这只是原始代码的一个随机版本,它将功能移动到单个调用 spawn_detached(callable) 中。即使在程序退出后,它也会使分离的进程保持运行:

import time
import os
from multiprocessing import Process, current_process

def spawn_detached(callable):
    p = _spawn_detached(0, callable)
    # give the process a moment to set up
    # and then kill the first child to detach
    # the second.
    time.sleep(.001)
    p.terminate()

def _spawn_detached(count, callable):
    count += 1
    p = current_process()
    print 'Process #%d: %s (%d)' % (count, p.name, p.pid)

    if count < 2:
        name = 'child'
    elif count == 2:
        name = callable.func_name
    else:
        # we should now be inside of our detached process
        # so just call the function
        return callable()

    # otherwise, spawn another process, passing the counter as well
    p = Process(name=name, target=_spawn_detached, args=(count, callable)) 
    p.daemon = False 
    p.start()
    return p

def operation():
    """ Just some arbitrary function """
    print "Entered detached process"
    time.sleep(15)
    print "Exiting detached process"


if __name__ == "__main__":
    print 'starting main', os.getpid()
    p = spawn_detached(operation)
    print 'exiting main', os.getpid()

https://stackoverflow.com/questions/13095878/

相关文章:

c# - PDFSharp 使用 PdfTextField 作为位置和大小引用在 pdf 中插入图像

nginx - 在 nginx 托管上出现 502 错误网关错误

winapi - 使用 NtOpenKey 时重定向注册表访问的正确方法是什么?

authentication - 如何使用 JavaMail 调试 SMTP 身份验证错误?

python - 是否可以在 Pandas 中将 searchsorted 与 MultiIndex

c# - 执行相机预览镜像模式的正确方法

html5-video - HTML5 视频自动播放是否适用于三星智能电视?

python - 组装字节码 - PyCode New

php - DOMDocument::save[domdocument.save]:无法打开流:权限

ruby-on-rails - 在 rails 3 中连接两个表