Ubuntu – Warning when available RAM approaches zero

memory usageram

This is a follow-up to Memory limiting solutions for greedy applications that can crash OS?: ulimit and cgroups are not user friendly, and besides, wouldn't work with applications that spawn separate processes, such as Chrome/Chromium for each new (group of) tabs.

The simple and effective solution, used by Windows 7 actually, is to warn the user that the OS is running low on memory. This simple warning pop-up has prevented me from having any low-memory-caused system freeze in Windows, while I kept running into them on Ubuntu distros that I was testing live (where the RAM-mounted disk would eat up 2GB alone).

So, is there some way to automatically warn the user that the available RAM is nearing zero, without the user having to keep an eye on some memory monitoring gadget? Surely Conky could be configured to do that?

Best Answer

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();
?>
Related Question