How to kill a python child process created with subprocess.check_output() when the parent dies?

Your problem is with using subprocess.check_output – you are correct, you can’t get the child PID using that interface. Use Popen instead:

proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE)

# Here you can get the PID
global child_pid
child_pid =

# Now we can wait for the child to complete
(output, error) = proc.communicate()

if error:
    print "error:", error

print "output:", output

To make sure you kill the child on exit:

import os
import signal
def kill_child():
    if child_pid is None:
        os.kill(child_pid, signal.SIGTERM)

import atexit

Leave a Comment