Is it safe to ignore the return value of Popen?

Viewed 60

I need that my python (2.7) program starts a sub-process and that it continues its processing while the child process is running. So I don’t want the main program to wait for the sub-process termination.

This is apparently achieved with Popen that returns a class object.

Is it safe to ignore the return value of Popen ?

Does the garbage collector delete the popen object ? Is the object garbage collected after the sub-process terminated ?

I can’t answer these questions with the python documentation.

Note that I’m using python 2.7 because of constrains I have no control on.

1 Answers

On Unix-like systems, failing to wait() on children creates zombies. This is a problem because you are polluting and eventually exhausting your process table. See https://en.wikipedia.org/wiki/Wait_(system_call)

If you want to kill your child process when your program finishes, do that. That's precisely why you need to save the result from Popen().

child = Popen(['sleep', '1234567890'])
# ... code happens ...
child.kill()
child.wait()

Just to reiterate, the Python object returned by Popen() is of course going to go away when Python goes away; the problem is that you also need to clean up the actual OS process which it represents.

Related