Warning when available RAM approaches zero
Check these scripts: Need application/script alerting when system memory is running out
#!/bin/bash
#Minimum available memory limit, MB
THRESHOLD=400
#Check time interval, sec
INTERVAL=30
while :
do
free=$(free -m|awk '/^Mem:/{print $4}')
buffers=$(free -m|awk '/^Mem:/{print $6}')
cached=$(free -m|awk '/^Mem:/{print $7}')
available=$(free -m | awk '/^-\/+/{print $4}')
message="Free $free""MB"", buffers $buffers""MB"", cached $cached""MB"", available $available""MB"""
if [ $available -lt $THRESHOLD ]
then
notify-send "Memory is running out!" "$message"
fi
echo $message
sleep $INTERVAL
done
PHP:
#!/usr/bin/php
<?php
$alert_percent=($argc>1)?(int)$argv[1]:90;
//$interval=($argc>2):(int)$argv[2]:25;
//while(true)
//{
exec("free",$free);
$free=implode(' ',$free);
preg_match_all("/(?<=\s)\d+/",$free,$match);
list($total_mem,$used_mem,$free_mem,$shared_mem,$buffered_mem,$cached_mem)=$match[0];
$used_mem-=($buffered_mem+$cached_mem);
$percent_used=(int)(($used_mem*100)/$total_mem);
if($percent_used>$alert_percent)
exec("notify-send 'Low Memory: $percent_used% used'");
//sleep($interval);
//}
exit();
?>
Another script that I wrote for this purpose:
#!/bin/bash
# Copyright 2019, Mikko Rantalainen
# License: MIT X License
# Minimum available memory until warning, default to 10% of total RAM (MiB)
THRESHOLD=$(grep "MemTotal:" /proc/meminfo | awk '{ printf "%d", 0.1*$2/1024}')
INTERVAL=60s
echo "Emitting a warning if less than $THRESHOLD MiB of RAM is available..."
while true; do
meminfo=$(cat /proc/meminfo)
free=$(echo "$meminfo" | grep "MemFree:" | awk '{ printf "%d", $2/1024}')
available=$(echo "$meminfo" | grep "MemAvailable:" | awk '{ printf "%d", $2/1024}')
inactive=$(echo "$meminfo" | grep "Inactive:" | awk '{ printf "%d", $2/1024}')
reclaimable=$(echo "$meminfo" | grep "SReclaimable:" | awk '{ printf "%d", $2/1024}')
usable=$(echo "$free + $inactive / 2 + $reclaimable / 2" | bc)
if test -z "$available"; then
message="Current kernel does not support MemAvailable in /proc/meminfo, aborting"
notify-send "Error while monitoring low memory" "$message"
echo "$message" 1>&2
exit 1
fi
message="Available: $available MiB
Free: $free MiB
Maybe usable: $usable MiB"
if [ "$available" -lt "$THRESHOLD" ]
then
notify-send -u critical "Low memory warning" "$message"
echo "Low memory warning:"
echo "$message"
fi
#echo "DEBUG: $message"
sleep $INTERVAL
done