【问题标题】:Python: Wait for "child process termination" OR "new connection"Python:等待“子进程终止”或“新连接”
【发布时间】:2015-09-13 07:25:42
【问题描述】:

我需要实现这样的东西:

while True:
    conn,addr = socket.accept()
    restore()
    p.kill()

    #...
    p = subprocess.Popen(...)

但我需要 restore() 函数不仅在每次新连接后被调用,而且在 p 死亡时也被调用。

我可以通过执行p.wait()“阻止”我的程序等待 p 死亡,但同时我也希望阻止我的程序等待新的连接。

换句话说,我需要阻止我的程序,直到这两个条件之一为真:“p dies”或“new connection”。

我知道我可以使用select 来等待两个文件描述符,但我不知道在这种情况下该怎么做。

谢谢

【问题讨论】:

标签: python subprocess python-multiprocessing python-sockets


【解决方案1】:

这是我最终使用的解决方案:

def wait_socket_and_process(s,process):
    while True:
        rr,_,_ = select.select([s],[],[],0.1)
        if len(rr)>0:
            conn, addr = rr[0].accept()
            process.kill()
            process.poll()
            #handle process termination
            print "* subprocess killed"
            return conn, addr

        elif (process.poll() != None):
            #handle process termination
            print "* subprocess terminated"


s = socket.#...
process = subprocess.Popen(...)
wait_socket_and_process(s,process)
#handle new connection...

正如其他人所建议的那样,使用 getenv 等库可能会有更简洁/更通用的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-08
    • 2010-09-25
    • 1970-01-01
    • 2020-09-09
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    相关资源
    最近更新 更多