0

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.

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.

In other words, I need to block my program until one of these two conditions is true : "p dies" OR "new connection".

I know I can use select to wait for two file descriptors, but I don't know how to do in this case.

Thanks

user975176
  • 428
  • 5
  • 16
  • Use gevent (http://www.gevent.org), and your code with p.wait() will just work the way you want – mguijarr Sep 13 '15 at 07:30
  • you could [use `signal.set_wakeup_fd()` to integrate `p.wait()` into `select()` loop](http://stackoverflow.com/q/30087506/4279). You could probably use `asyncio`/`twisted`/`gevent` instead of reimplementing the functionality yourself. – jfs Sep 13 '15 at 16:20

1 Answers1

0

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.

user975176
  • 428
  • 5
  • 16