subprocess becomes defunct, `communicate()` hangs

2k views Asked by At

In python 2.7 on Ubuntu 14.04, I launch a process like this:

bag_process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for i in range(5):
    print "Countdown: {}".format(5 - i - 1)
    time.sleep(1)
print "Sending SIGINT to PID {}".format(bag_process.pid)
bag_process.send_signal(signal.SIGINT)
(bag_out, bag_err) = bag_process.communicate()

The program hangs on the communicate() line. When I open another terminal, I run ps -ef | grep ### to find the pid of the subprocess, and I see it's <defunct>.

Why is the child program becoming defunct, and the parent program hanging on communicate()? Provided that the child truly exits after receiving SIGINT, how can I make the parent program reliably handle that without hanging?

1

There are 1 answers

0
Edward Ned Harvey On

The problem was: Don't kill a process like this:

bag_process.send_signal(signal.SIGINT)

Instead, kill the process and all of its sub-processes like this:

parent = psutil.Process(bag_process.pid)
for child in parent.get_children(recursive=True):
    child.send_signal(signal.SIGINT)
bag_process.send_signal(signal.SIGINT)