0

问题:我希望孩子超时并完成。但相反,它超时并再次开始运行。

谁能告诉我为什么这个程序永远运行?我希望它运行一次并退出......

这是一个工作程序。Master线程一个函数来产生一个孩子。效果很好,除了它最终循环。

这里是大师:

# master.py
import multiprocessing, subprocess, sys, time

def f():
    p = subprocess.Popen(["C:\\Python32\\python.exe", "child.py"])
    # wait until child ends and check exit code
    while p.poll() == None:
        time.sleep(2)
    if p.poll() != 0:
        print("something went wrong with child.py")

# multithread a function process to launch and monitor a child
p1 = multiprocessing.Process(target = f())
p1.start()

和孩子:

# child.py
import socket, sys

def main(args):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(10)
        sock.bind(('', 54324))
        data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
        print(data)
        sock.close()
        return 0
    except KeyboardInterrupt as e:
        try:
            sock.close()
            return 0
        except:
            return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))
4

1 回答 1

1

问题是你master.py没有if __name__ == '__main__'警卫。在 Windows 上,multiprocessing必须能够main在子进程中重新导入模块,如果您不使用此if保护,您将在子进程中重新执行multiprocessing.Process(导致意外 forkbomb)。

要修复,只需将所有命令放入master.py防护中if

if __name__ == '__main__':
    # multithread a function process to launch and monitor a child
    p1 = multiprocessing.Process(target = f())
    p1.start()
于 2012-09-21T02:28:09.873 回答