Dariusz on Software Quality & Performance

25/05/2011

Kill whole tree of processes on Linux

Filed under: en — Tags: — dariusz.cieslak @

Since few months I'm responsible for managing build server that perfrorms regular builds for testing purposes. Sometimes I need to stop whole build job on server (probably composed of many processes). On Linux when parent process is killed all childen are not affected and are reallocated to init (PID=1) process. I'd like to stop them as well.

You can of course list process with hierarchy and kill processes manually:

ps xf
kill ... ...

But there's faster, automated, metod.

In order to kill process (given by $PID) and all subprocesses easilly you can use the following command:

kill $(ps -o pid= -s $(ps -o sess --no-heading --pid $PID))

Update 2011-12-17: there's alternative way to kill whole subtree that might be more accurate and depends on "ps xf" output:

ps xf | awk -v PID=$PID '
    $1 == PID { P = $1; next }
    P && /_/ { P = P " " $1; K=P }
    P && !/_/ { P="" }
    END { print "kill " K }'\
    | sh -x

2 Comments »

  1. Thank you very much. I was looking for a such short code for a long time.

    Comment by Alex — 02/10/2011 @

  2. Awesome one-liner!

    Comment by Anonymous — 10/01/2013 @

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress