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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 11 views 0 copies

Python code

34 lines
Python 3.9+
import 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

stdout
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

  1. Use `pgrep -f '' demo` to list matching PIDs before checking their state
  2. 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

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.