python主/子无意中循环

时间:2012-09-20 22:26:40

标签: python sockets windows-7 python-3.x subprocess

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

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

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

这是主人:

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

0 个答案:

没有答案