Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

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.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Python code

31 lines
Python 3.9+
#!/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

stdout
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

  1. Read the /proc filesystem directly by listing directories under /proc and checking the `status` or `stat` file for state.
  2. 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

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.