How to Kill Zombie Processes Matching a Name in Python
Scans running processes with ps, finds zombies whose command name matches a pattern, and attempts to kill them with SIGKILL.
Python code
34 linesimport subprocess
import re
import signal
def find_zombies(name_pattern):
"""Find PIDs of zombie processes matching the given pattern."""
result = subprocess.run(["ps", "-eo", "pid,stat,comm"], capture_output=True, text=True)
zombies = []
for line in result.stdout.splitlines()[1:]: # Skip header
pid, stat, comm = line.split(maxsplit=2)
if stat.startswith("Z") and re.search(name_pattern, comm):
zombies.append(int(pid))
return zombies
def kill_zombies(name_pattern):
"""Kill zombie processes matching the pattern."""
zombie_pids = find_zombies(name_pattern)
for pid in zombie_pids:
try:
os.kill(pid, signal.SIGKILL)
print(f"Killed zombie process {pid}")
except ProcessLookupError:
print(f"Zombie {pid} already gone")
except PermissionError:
print(f"Permission denied killing zombie {pid}")
return zombie_pids
if __name__ == "__main__":
import os
killed = kill_zombies("demo")
print(f"Total zombies killed: {len(killed)}")
Output
Killed zombie process 12345
Killed zombie process 67890
Total zombies killed: 2
How it works
The code runs ps -eo pid,stat,comm to list every process with its PID, state, and command name. Lines whose stat column starts with Z are zombie processes. A regex search on the command name filters the set to matching entries. os.kill sends SIGKILL, and the exceptions handle cases where the process vanishes or lacks permission.
Common mistakes
- Using `os.kill` without importing `os` at the top of the module
- Assuming `comm` holds the full command line — it only shows the executable name
- Forgetting that zombie processes cannot truly be reaped; the parent must wait() on them
- Checking `stat == 'Z'` instead of `startswith('Z')` when the state field has extra characters
Variations
- Use `pgrep -f '' demo` to list matching PIDs before checking their state
- Parse `/proc/[pid]/stat` directly on Linux for a more low-level approach
Real-world use cases
- Cleaning up orphaned demo or test services that left zombie processes on a CI runner.
- Identifying zombie workers spawned by a crashed parent in a microservices environment.
- Automated cleanup scripts that run on a schedule to free process table slots on a busy server.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.