2

I have a script that starts an another script2.py as subprocesses. But when I close the terminal, script2.py still stays runned. How can I terminate a subprocess when closing the terminal(console).

Here is how I start the subprocess:

p = subprocess.Popen(command,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        shell=True)
    command_output = iter(p.stdout.readline, b'')

And I normally close it like this: os.killpg(os.getpgid(p.pid), signal.SIGTERM), but how to terminate all subprocesses just by closing the console(terminal)?

passwd
  • 2,883
  • 3
  • 12
  • 22
  • As part of the command to start script2.py, send console/script1.py pid, In script2.py, run a thread to check if pid of script1 exists, as soon pid is lost, exit/close script2 – be_good_do_good Sep 19 '16 at 18:07
  • Possible duplicate of [Ensuring subprocesses are dead on exiting Python program](http://stackoverflow.com/questions/320232/ensuring-subprocesses-are-dead-on-exiting-python-program) – albert Sep 19 '16 at 18:32
  • 1
    Also possible duplicate of [How to terminate a python subprocess launched with shell=True](http://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true) – mgarey Sep 19 '16 at 18:49

0 Answers0