Skip to content

Instantly share code, notes, and snippets.

@jugglinmike
Last active December 30, 2015 10:09
Show Gist options
  • Save jugglinmike/7814130 to your computer and use it in GitHub Desktop.
Save jugglinmike/7814130 to your computer and use it in GitHub Desktop.
A factory function for safely waiting for (and interacting with) zombie processes.
from contextlib import contextmanager
@contextmanager
def zombie(process):
proc_file_name = '/proc/' + str(process.pid) + '/stat'
while True:
with open(proc_file_name, 'r') as proc_file:
if proc_file.readline().split(' ')[2] == 'Z':
yield process
break
# Reap the process
process.poll()
# Example usage:
import subprocess
process = subprocess.Popen( ('sleep', '1'), stdout=subprocess.PIPE)
# Listed as `active` in the process table:
subprocess.call( ('ps', '-l') )
with zombie(process):
# Listed as `zombie` in the process table
subprocess.call( ('ps', '-l') )
# 'Do stuff with the zombie process'
# No longer listed in process table:
subprocess.call( ('ps', '-l') )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment