简体   繁体   English

Python:等待“子进程终止”或“新连接”

[英]Python: Wait for “child process termination” OR “new connection”

I need to implement something like this: 我需要实现这样的事情:

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

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

But I need that the restore() function is called not only after every new connection, but also as soon as p dies. 但是我不仅需要在每个新连接之后都调用restore()函数,而且还必须在p终止时调用该函数。

I can "block" my program waiting for p death by doing p.wait() , however I also want, at the same time, to block my program waiting for a new connection. 我可以通过执行p.wait()来“阻止”等待p死亡的程序,但是同时,我也想阻止等待新连接的程序。

In other words, I need to block my program until one of these two conditions is true : "p dies" OR "new connection". 换句话说,我需要阻塞程序,直到这两个条件之一成立:“ p dies”或“新连接”。

I know I can use select to wait for two file descriptors, but I don't know how to do in this case. 我知道可以使用select等待两个文件描述符,但是在这种情况下我不知道该怎么做。

Thanks 谢谢

This is the solution I ended up using: 这是我最终使用的解决方案:

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...

As others suggest, there may be cleaner/more general ways to do so using libaries like getenv . 正如其他人所建议的那样,使用getenv库可能会有更清洁/更通用的方法来实现此目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM