Last active
November 7, 2023 00:03
-
-
Save swarminglogic/8666556 to your computer and use it in GitHub Desktop.
nicekill: A bash script to terminate a process in the order of SIGTERM, SIGINT, SIGHUP, SIGKILL, giving each signal 2 seconds to enact.
This file contains 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 | |
# $1: PID | |
# Returns true if a process exists with pid=PID | |
function isProcessAlive { | |
if [ `ps -p $1 | wc -l` -gt 1 ] ; then | |
return 0; | |
else | |
return 1; | |
fi | |
} | |
# 1:$PID, $2:SIGNAL | |
# Attempts to kill process-pid PID, using signal SIGNAL | |
# It checks to see if it succeeded every 0.1 seconds for 2 seconds. | |
# Returns true if success, false otherwise | |
function killProcess { | |
kill -$2 $1 | |
sleep 0.1 | |
for i in {0..19} ; do | |
if isProcessAlive $1 ; then | |
sleep 0.1; | |
else | |
return 0; | |
fi | |
done | |
return 1; | |
} | |
# $1:PID, $2:SIGNAL, $3:SIGNAL-TEXT | |
function writeSucess { | |
echo "Process $1 terminated with signal $2 (SIG$3)"; | |
exit | |
} | |
# $1:PID, $2:SIGNAL, $3:SIGNAL-TEXT | |
function attemptKill { | |
if killProcess $1 $2 ; then writeSucess $1 $2 $3 ; fi | |
} | |
if [ $# -eq 0 ] ; then | |
echo "Usage: ./nicekill ProcessID" | |
fi | |
if isProcessActive $1 | |
then | |
attemptKill $1 15 TERM | |
attemptKill $1 2 INT | |
attemptKill $1 1 HUP | |
attemptKill $1 9 KILL | |
# Attempt to remove with | |
echo "Failed to terminate process $1." | |
ps -p $1 | |
else | |
echo "No process found with id $1." | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment