Last active
May 18, 2023 11:48
-
-
Save hrz6976/79f44a076d36450c97970c57d4c111d2 to your computer and use it in GitHub Desktop.
Checks the memory usage and kill the process occupying the most mem regularly
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
# copy it to /etc/cron.d | |
*/5 * * * * root test -f /home/user/kill-before-oom/kill-before-oom.sh && bash /home/user/kill-before-oom/kill-before-oom.sh >> /home/user/kill-before-oom/kill-before-oom.log 2>&1 |
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 | |
set -e | |
# Check memory usage | |
mem_usage=$(free | awk '/Mem/{print $3/$2 * 100.0}') | |
# If memory usage is above 98%, kill process with highest memory usage | |
if (( $(echo "$mem_usage > 98" | bc -l) )); then | |
pid_cmd="ps aux --sort=-%mem | awk 'NR==2{print $2}'" | |
pid=$(eval $pid_cmd) | |
pname=$(ps -p $pid -o comm=) | |
puser=$(ps -p $pid -o user=) | |
kill -9 $pid | |
logger "Killing process $pname with PID $pid due to high memory usage: $mem_usage %" | |
# send a message to the user | |
time=$(date) | |
echo "[$time] Killing process $pname with PID $pid due to high memory usage: $mem_usage %" | wall -n -u $puser | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment