1

I am trying to stop a server which is a subprocess when the parent process gets killed by a cntrl-D(EOF on stdin). I tried many ways including reading stdin in the subprocess but that blocks all keyboard input. Is there a way to kill the subprocess when the parent process encounters a EOF.

Creating a subprocess in python via subprocess.Popen

polling for EOF in subprocess by this:

self.t = threading.Thread(target=self.server.serve_forever)
self.t.start()
# quit on cntrl-d (EOF)
while True:
    if len(sys.stdin.readline()) == 0:
        self.stop()

def stop(self):
    manager.save()
    # shutdown bottle
    self.server.shutdown()
    # close socket
    self.server.server_close()
    self.t.join()
    sys.exit()
jack sexton
  • 1,227
  • 1
  • 9
  • 28
  • Let the parent process signal to the child that it's time to exit. – that other guy Jul 27 '16 at 17:06
  • @thatotherguy that doesn't work when a user forcibly exits the parent process with a control-d, there is not signal propagation there. – jack sexton Jul 27 '16 at 17:11
  • Ctrl-D is not forcible exit. In your snippet you appear to have explicitly coded to detect eof and exit because of. Just signal to the child that it should exit as part of that, e.g. with Python's thread events. – that other guy Jul 27 '16 at 17:21
  • @thatotherguy the code above is in the subprocess. I do not have access to the parent process. I'm trying to detect a control-D happening in the parent process so I can handle that in the subprocess with stop() – jack sexton Jul 27 '16 at 17:24
  • Ah. It's the parent process' job to handle this, but since it's failing as a parent you could e.g. loop until `os.getppid()` is 1, indicating that the parent process has exited and you've been reassigned to init. – that other guy Jul 27 '16 at 17:27
  • @thatotherguy I'll try that out, its a hack but at this point I don't mind. Thanks. – jack sexton Jul 27 '16 at 17:29
  • Related: http://stackoverflow.com/questions/13593223/making-sure-a-python-script-with-subprocesses-dies-on-sigint http://stackoverflow.com/questions/3791398/how-to-stop-python-from-propagating-signals-to-subprocesses – Tom Myddeltyn Jul 28 '16 at 13:25

1 Answers1

0

with @thatotherguy 's suggestion of using os.getppid(), here is the new working solution to end the child process when it is orphaned by the parent (ie. when a control-D occurs on the parent and it closes without signaling the child)

self.t = threading.Thread(target=self.server.serve_forever)
self.t.start()
# quit on cntrl-d (EOF)
if os.getppid() != 1:
    while True:
        if os.getppid() == 1:
            self.stop()
        else:
            time.sleep(1)
jack sexton
  • 1,227
  • 1
  • 9
  • 28