Skip to content

Instantly share code, notes, and snippets.

@neilellis
Last active August 29, 2015 14:02
Show Gist options
  • Save neilellis/3ef96135f71a15c61d9b to your computer and use it in GitHub Desktop.
Save neilellis/3ef96135f71a15c61d9b to your computer and use it in GitHub Desktop.
Kill a process tree
#!/bin/bash -eu
#From http://stackoverflow.com/questions/392022/best-way-to-kill-all-child-processes?lq=1
#See that URL for alternative methods which don't require pstree
function kill_tree() {
#$1 is the name of the process, i.e. the file that was executed
readonly gpid=$(pgrep -o $1)
#Now $gpid is the group id of all the sub processes
if [[ ! -z $gpid ]]
then
#So this is nasty, but the only sane way I have found to do this so far
#Take a look at what pstree produces as output and this mayhem will make sense
#Basically we're getting all the recursive child processes and then passing them
#To kill
kill -${2} $(pstree -p ${gpid} | sed 's/(/\n(/g' | grep '(' | sed 's/(\(.*\)).*/\1/' | tr "\n" " ")
else
echo "No process matching $1 found"
fi
}
# e.g kill_tree run-docker.sh -9
kill_tree $1 ${2:-9}
@neilellis
Copy link
Author

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