简体   繁体   English

在控制-D上退出子进程?

[英]Exiting subprocess on control-D?

I am trying to stop a server which is a subprocess when the parent process gets killed by a cntrl-D(EOF on stdin). 我试图阻止服务器,当父进程被cntrl-D(stdin上的EOF)杀死时,这是一个子进程。 I tried many ways including reading stdin in the subprocess but that blocks all keyboard input. 我尝试了很多方法,包括在子进程中读取stdin但阻止所有键盘输入。 Is there a way to kill the subprocess when the parent process encounters a EOF. 有没有办法在父进程遇到EOF时终止子进程。

Creating a subprocess in python via subprocess.Popen 通过subprocess.Popen在python中创建子subprocess.Popen

polling for EOF in subprocess by this: 通过以下方式轮询子进程中的EOF:

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

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) 使用@thatotherguy建议使用os.getppid(),这是一个新的工作解决方案,当父进程孤立时终止子进程(即,当父进程出现控制-D并且它关闭而没有发出信号时儿童)

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)

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

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