2015-02-20

How to prevent your Linux hangs when out of memory (OOM)

Sometimes when a software overusing our RAM, the Linux User Interface starts to lag and hangs (even when oom_kill_allocating_task enabled, and even when we're already using swapfile. This tutorial will let your ArchLinux automatically kill software with highest memory usage using a program named earlyoom. To install it, just type:

yaourt --needed --noconfirm -S --force earlyoom-git
sudo cp /usr/bin/earlyoom /usr/local/bin/
sudo systemctl enable earlyoom
sudo systemctl start earlyoom

Now try to compile and run this program:

echo '
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
    int max = -1;
    int mb = 0;
    char* buffer;
    if(argc > 1) max = atoi(argv[1]);
    while((buffer=malloc(1024*1024)) != NULL && mb != max) {
        memset(buffer,0,1024*1024);
        printf("Allocated %d MB\n", ++mb);
    }
    return 0;
}
' > munch.c && gcc -O2 -o munch munch.c 
./munch

It would give an output something like this:

Allocated 1 MB
Allocated 2 MB
Allocated 3 MB
...
Allocated 4367 MB
Allocated 4368 MB
Allocated 4369 MB

Killed

The program with highest memory usage now killed automatically and your system would be always responsive. To see the realtime log of service type journalctl -f -u earlyoom it would show something like this:

-- Logs begin at Mon 2014-11-03 10:54:39 WIB. --
Feb 20 13:25:25 s497 earlyoom[20041]: earlyoom v0.3-15-g528196e
Feb 20 13:25:25 s497 earlyoom[20041]: total:  7800 MiB
Feb 20 13:25:25 s497 earlyoom[20041]: min:     780 MiB
Feb 20 13:25:25 s497 earlyoom[20041]: avail:  4963 MiB
Feb 20 13:33:10 s497 earlyoom[20041]: Out of memory! avail: 519 MiB < min: 780 MiB
Feb 20 13:33:10 s497 earlyoom[20041]: Killing process 24984 (munch)

press Ctrl+C to close that command.