Kill Process Tree

From Shrubbery

Jump to: navigation, search


How to kill a process tree.

Here's a shell function that kills a tree of processes, based on the parent process id:

function killProcTree()
{
    local parentid=$1
    for child in $(ps axo pid,ppid | awk "{ if ( \$2 == $parentid ) { print \$1 }}")
    do
        echo "Killing child process $child because parent id is $parentid"
        kill $child
        KILLEXITCODE=$?
        if [ $KILLEXITCODE -ne 0 ]; then
            echo "PID $child not running"
        else
            echo "stopped PID $child "
        fi
    done
    kill -KILL $parentid 2>/dev/null
    KILLEXITCODE=$?
    if [ $KILLEXITCODE -ne 0 ]; then
        echo "PID $parentid not running"
    else
        echo "stopped PID $parentid"
    fi
}

This is often useful for killing a JBoss process that was started with the run.sh script.

See also:

Personal tools