How to identify percentage of memory usage for running cache clean command?

Asked

Viewed 838 times

0

We know that the command for memory cache cleanup is this:

sync; echo 3 > /proc/sys/vm/drop_caches

However, how to make an executable with a condition (if() Else()), so that this command is executed only when memory usage reaches 80% or more through crontab?

Something like this:

#!/bin/sh
if (uso da memoria > 80%){
    sync; echo 3 > /proc/sys/vm/drop_caches
}
  • Hi Anderson. What part are you struggling with? Do the if in batch script? Extract the percentage of memory used? Set up job in cron? If you prepare a mvce demonstrating the problem becomes easier to help.

  • my difficulty is in making an if according to the percentage of memory used. do not know where to start.

1 answer

2

I solved my problem with the code below:

#!/bin/bash

# total de memória instalada  32991100 (32 GB)

# total em 90% de uso 29691990

MAXIMO="29691990"

MONITOR=$(free | grep Mem)
USADA=$(echo $MONITOR | awk '{ print $3 }')
LIVRE=$(echo $MONITOR | awk '{ print $4 }')

if [ "$USADA" -gt "$MAXIMO" ]
then
    sync; echo 3 > /proc/sys/vm/drop_caches
fi

The cron task will run every 5 minutes and if it identifies that memory usage is above 90%, it will clear the memory cache.

  • 2

    You may know this, but it’s still nice to have the information here. Clearing the VM cache on Linux just to free up memory is almost always a bad idea. Linux always tries to use as much memory as possible to optimize performance, and when it really needs application memory, it tries to clear the least "important" cache pages. When you force the cleaning of the entire cache, pro Linux will not make as much difference in terms of free memory, but you lose all the performance you would gain with very accessed files straight from memory.

  • I really agree with you, Eitch, this is not good practice, but it depends on the situation. I have a web server and I am obliged to do this since I cannot restart the machine when the memory cache is full. Then this solution fell to me like a glove. Moreover in my situation the cleaning occurs every 2 days. So in case of performance will not be much affected.

  • 1

    But that’s it, why are you obliged to do this to clear the cache? After all, if Linux needs memory, it displaces the cache in the same way to get more memory for the application :)

  • I started doing this after I noticed a slowdown on the server and that no application responded due to memory being 100% used. Maybe then there is another configuration to do, because if I do not use this practice in a few hours my server "freezes".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.