Skip to content

Instantly share code, notes, and snippets.

@nickpeirson
Last active May 15, 2023 06:30
Show Gist options
  • Save nickpeirson/099b372fc5ad7cf6f080f3d087850631 to your computer and use it in GitHub Desktop.
Save nickpeirson/099b372fc5ad7cf6f080f3d087850631 to your computer and use it in GitHub Desktop.
Script to clean Zombie processes up using gdb
#!/bin/bash
##################################################################
# Script: Zombie Slayer
# Author: Mitch Milner
# Date: 03/13/2013 ---> A good day to slay zombies
#
# Requirements: yum install gdb / apt-get install gdb
# permissions to attach to the parent process
#
# This script works by using a debugger to
# attach to the parent process and then issuing
# a waitpid to the dead zombie. This will not kill
# the living parent process.
##################################################################
clear
# Wait for user input to proceed, give user a chance to cancel script
echo "***********************************************************"
echo -e "This script will terminate all zombie process."
echo "***********************************************************"
# initialize variables
intcount=0
lastparentid=0
# remove old gdb command file
rm -f /tmp/zombie_slayer.txt
# create the gdb command file
echo "***********************************************************"
echo "Creating command file..."
echo "***********************************************************"
ls /proc | grep -P '\d' | while read PID; do
state=$([ -f /proc/$PID/status ] && awk '/^State/{ print $2}' /proc/$PID/status)
if [ "$state" != "D" ]; then
continue
fi
intcount=$((intcount+1))
parentid=$(awk '/^PPid/{ print $2}' /proc/$PID/status)
zombieid=$PID
if [ "$parentid" != "$lastparentid" ]; then
if [ "$lastparentid" != "0" ]; then
echo "detach" >> /tmp/zombie_slayer.txt
fi
echo "attach $parentid" >> /tmp/zombie_slayer.txt
fi
echo "call waitpid ($zombieid,0,0)" >> /tmp/zombie_slayer.txt
lastparentid=$parentid
done
if [ "$lastparentid" != "0" ]; then
echo "detach" >> /tmp/zombie_slayer.txt
fi
# Slay the zombies with gdb and the created command file
echo -e "\n\n"
echo "***********************************************************"
echo "Slaying zombie processes..."
echo "***********************************************************"
gdb -batch -x /tmp/zombie_slayer.txt
echo -e "\n\n"
echo "***********************************************************"
echo "Script complete."
echo "***********************************************************"
@nickpeirson
Copy link
Author

Modified the original script to get zombie processes from /proc, rather than ps, as I was trying to use this on a server where ps was hanging.

I also removed the confirmation prompt and did a little reformatting.

@vyakovlev
Copy link

vyakovlev commented Apr 19, 2022

I guess, state != Z instead of D

Thanks for a great implementation of the idea!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment