Last active
May 5, 2022 08:15
-
-
Save gyakkun/72b85bd59db80e89fce50a2d626469b0 to your computer and use it in GitHub Desktop.
Kill Shell Subprocess Recursively
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 | |
| # Kill Subprocesses Recursively | |
| RECURSIVE_WARNING_THRESHOLD=20 | |
| RECURSIVE_ERROR_THRESHOLD=50 | |
| debug(){ | |
| echo "DEBUG: $*" | |
| } | |
| warn(){ | |
| echo "WARNING: $*" | |
| } | |
| error(){ | |
| echo "ERROR: $*" >&2 | |
| } | |
| kill_recursively() { | |
| local PID=$1 | |
| if [ -z $PID ]; then | |
| error "No PID specified. Returning" | |
| return; | |
| fi | |
| local LAYER=$2 | |
| if [ -z $LAYER ]; then | |
| LAYER=0 | |
| fi | |
| debug "Recursive layer: $LAYER" | |
| if [ $LAYER -gt $RECURSIVE_ERROR_THRESHOLD ]; then | |
| error "Current recursive layer is over $RECURSIVE_ERROR_THRESHOLD, exiting." | |
| return; | |
| fi | |
| if [ $LAYER -gt $RECURSIVE_WARNING_THRESHOLD ]; then | |
| warn "Current recursive layer is over threshold $RECURSIVE_WARNING_THRESHOLD" | |
| fi | |
| local subprocess=`pgrep -P $PID` | |
| if [[ -z $subprocess ]]; then | |
| debug "No more subprocess, committing suicide: $PID" | |
| # kill -9 $PID | |
| return; | |
| fi | |
| for sp in $subprocess; do | |
| debug "Looping PID is $sp" | |
| kill_recursively $sp $(expr $LAYER + 1) | |
| done; | |
| debug "Finally commit suicide : $PID" | |
| # kill -9 $PID | |
| } | |
| ARG_COUNT=$# | |
| debug "Arg count: $ARG_COUNT" | |
| if [ $ARG_COUNT -le 0 ]; then | |
| error "No PID specified!" | |
| exit 1 | |
| fi | |
| PID=$1 | |
| debug "Root PID : $PID" | |
| if [ $PID -le 1 ]; then | |
| error "Should never kill systemd and its root process!" | |
| exit 1 | |
| fi | |
| kill_recursively $PID |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment