Skip to content

Instantly share code, notes, and snippets.

@hrz6976
Last active May 18, 2023 11:48
Show Gist options
  • Save hrz6976/79f44a076d36450c97970c57d4c111d2 to your computer and use it in GitHub Desktop.
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
# 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
#!/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