linux - [Solved-5 Solutions] Best way to kill all child processes in Linux - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

What is the best way to kill all child processes in Linux ?

Linux - Solution 1:

If you need to kill is a single process group. (This is often the case if the tree is the result of forking from a server start or a shell command line.) You can discover process groups using GNU ps as follows:

 ps x -o  "%p %r %y %x %c "
click below button to copy the code. By - Linux tutorial - team

If it is a process group you want to kill, just use the kill(1) command but instead of giving it a process number, give it the negation of the group number. For example to kill every process in group 5112, use kill -TERM -- -5112.

Linux - Solution 2:

pkill -TERM -P 27888
click below button to copy the code. By - Linux tutorial - team

This will kill all processes that have the parent process ID 27888.

CPIDS=$(pgrep -P 27888); (sleep 33 && kill -KILL $CPIDS &); kill -TERM $CPIDS
click below button to copy the code. By - Linux tutorial - team

which schedule killing 33 second later and politely ask processes to terminate.

Linux - Solution 3:

To kill a process tree recursively, use killtree():

#!/bin/bash

killtree() {
    local _pid=$1
    local _sig=${2:--TERM}
    kill -stop ${_pid} # needed to stop quickly forking parent from producing children between child killing and parent killing
    for _child in $(ps -o pid --no-headers --ppid ${_pid}); do
        killtree ${_child} ${_sig}
    done
    kill -${_sig} ${_pid}
}

if [ $# -eq 0 -o $# -gt 2 ]; then
    echo "Usage: $(basename $0) <pid> [signal]"
    exit 1
fi

killtree $@
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

for child in $(ps -o pid -ax --ppid $PPID) do ....... done
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

for child in $(ps -o pid,ppid -ax | \
   awk "{ if ( \$2 == $pid ) { print \$1 }}")
do
  echo "Killing child process $child because ppid = $pid"
  kill $child
done
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - Best way to kill all child processes