Shell script implements checking and killing child processes and zombie processes

Time:2022-6-18

There are a lot of scripts and programs running on the core server. It is inevitable that sometimes zombie processes will appear. Zombie processes will occupy resources there. At first, I just wrote a Linux shell script to check and kill processes according to keywords. Later, I found that when a process dies there, it is actually a problem when calling child processes internally. At this time, killing the parent process alone does not solve the fundamental problem. For example, Rsync connects through SSH. Rsync itself is OK, but SSH may die. Therefore, the script is rewritten to recursively find child processes.

Copy codeThe codes are as follows:
#!/bin/sh
#Recursively find the lowest level child process that causes the process to freeze and kill it
ParentProcessID=$1;
if [ “x${ParentProcessID}” = “x” ] ; then
    echo “Please Supply the top Parent Process ID to be killed!”
    echo “Usage:sh $0 PID [-v]”
    echo “PID The Parent Process ID as root”
    echo “-v is this argument supplied,no real kill operation will be performed,only process tree be show.”
    exit 1
fi

let IsRealKillDo=1;
if [ “x$2” = “x-v” ] ; then
    let IsRealKillDo=0;
fi

echo “Begin Kill the Leaf Process of process ${ParentProcessID}” >&2

killpidList=””

function loopNextSubProcess(){
    local nParentProcessID=$1
    local tmpPidList=””
    tmpPidList=`ps -A –format=’%p%PisParent’ –width 2048 -w –sort pid|grep “${nParentProcessID}isParent”|grep -v grep|grep -v “$$” | awk ‘{ printf $1 }’`
    ps –format=’%p%P%a’ –width 2048 -w -p ${nParentProcessID}|grep -v grep|grep -v “$$” >&2
    if [ “x${tmpPidList}” = “x” ] ; then
        echo “****Got One Leaf = [${nParentProcessID}]****” >&2
        killpidList=”${killpidList}\n${nParentProcessID}”
        return
    fi

    for theNextPid in ${tmpPidList} ; do
        loopNextSubProcess ${theNextPid}
    done
}

loopNextSubProcess ${ParentProcessID}

if [ ${IsRealKillDo} -eq 1 -a “x${killpidList}” != “x” ] ; then
    for curpid in `echo -e ${killpidList}` ; do
        if [ “x${curpid}” != “x” ] ; then
            echo “kill -9 ${curpid}”
            kill -9 ${curpid}
        fi
    done
else
    echo -e ${killpidList}
fi