Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
Python code
31 lines#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.strip().split('\n')[1:]: # Skip header
if line.strip():
parts = line.split()
if len(parts) >= 3:
pid, state, command = parts[0], parts[1], ' '.join(parts[2:])
if 'Z' in state:
zombies.append((int(pid), command))
return zombies
except subprocess.CalledProcessError:
return []
def main():
zombies = find_zombie_processes()
if zombies:
print("Zombie processes found:")
for pid, command in zombies:
print(f" PID {pid}: {command}")
else:
print("No zombie processes found.")
if __name__ == "__main__":
main()
Output
Zombie processes found:
PID 1234: defunct_program
PID 5678: old_service
How it works
Zombie processes are terminated but still have an entry in the process table because their parent has not read their exit status. The ps -eo pid,stat,comm command lists each process with its PID, state code, and command name. State Z indicates a zombie. By iterating over the output lines and checking for 'Z' in the state field, we collect all zombies. Using subprocess.run with check=True ensures errors (e.g., if ps is unavailable) are caught gracefully.
Common mistakes
- Parsing header line as a process entry (always skip the first line).
- Assuming the state field always appears as a single character (it can be multi-character like 'Zs' for zombie+session leader).
- Forgetting to handle the case where `ps` output columns might not have spaces consistently.
Variations
- Read the /proc filesystem directly by listing directories under /proc and checking the `status` or `stat` file for state.
- Use the `pgrep` or `psutil` third-party library for cross-platform process monitoring.
Real-world use cases
- Integrate into a system health monitoring script that alerts when zombie processes accumulate on a production server.
- Use inside a CI/CD pipeline to check for orphaned processes after test runs and clean them up automatically.
- Wrap in a cron job that logs zombie process counts each hour for capacity planning and anomaly detection.
Sponsored
More from Automation & scripting
- 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
- Automatically Log CPU, RAM, and Disk Usage Every Minute in Python easy
- Batch Rename Hundreds of Files in Python easy
Keep learning
Related tutorials and quizzes for this topic.