Last active
August 29, 2015 14:02
-
-
Save neilellis/3ef96135f71a15c61d9b to your computer and use it in GitHub Desktop.
Kill a process tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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} |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also see http://stackoverflow.com/questions/392022/best-way-to-kill-all-child-processes?lq=1