15 September, 2015

How do you empty the buffers and cache on a Linux ?

Emptying the buffers cache

If you ever want to empty it you can use this chain of commands.
# free && sync && echo 3 > /proc/sys/vm/drop_caches && free

             total       used       free  shared    buffers     cached
Mem:       1018916     980832      38084       0      46924     355764
-/+ buffers/cache:     578144     440772
Swap:      2064376        128    2064248
             total       used       free  shared    buffers     cached
Mem:       1018916     685008     333908       0        224     108252
-/+ buffers/cache:     576532     442384
Swap:      2064376        128    2064248
You can signal the Linux Kernel to drop various aspects of cached items by changing the numeric argument to the above command.
  • To free pagecache:
    # echo 1 > /proc/sys/vm/drop_caches
    
  • To free dentries and inodes:
    # echo 2 > /proc/sys/vm/drop_caches
    
  • To free pagecache, dentries and inodes:
    # echo 3 > /proc/sys/vm/drop_caches
    
The above are meant to be run as root. If you're trying to do them using sudo then you'll need to change the syntax slightly to something like these:
 
$ sudo sh -c 'echo 1 >/proc/sys/vm/drop_caches'
$ sudo sh -c 'echo 2 >/proc/sys/vm/drop_caches'
$ sudo sh -c 'echo 3 >/proc/sys/vm/drop_caches'

NOTE: There's a more esoteric version of the above command if you're into that:
 
$ echo "echo 1 > /proc/sys/vm/drop_caches" | sudo sh

Why the change in syntax? The /bin/echo program is running as root, because of sudo, but the shell that's redirecting echo's output to the root-only file is still running as you. Your current shell does the redirection before sudo starts.

Swap

If you want to clear out your swap you can use the following commands.
$ free
             total       used       free     shared    buffers     cached
Mem:       7987492    7298164     689328          0      30416     457936
-/+ buffers/cache:    6809812    1177680
Swap:      5963772     609452    5354320

Then use this command to disable swap:
$ swapoff -a

You can confirm that it's now empty:
$ free
             total       used       free     shared    buffers     cached
Mem:       7987492    7777912     209580          0      39332     489864
-/+ buffers/cache:    7248716     738776
Swap:            0          0          0

And to re-enable it:
$ swapon -a

And now reconfirm with free:
$ free
             total       used       free     shared    buffers     cached
Mem:       7987492    7785572     201920          0      41556     491508
-/+ buffers/cache:    7252508     734984
Swap:      5963772          0    5963772


A more hammer and nail approach:

cat /dev/zero > /tmp/cache.cleaner ; rm -f /tmp/cache.cleaner

This even doesn't need root access!
(Assuming your /tmp is mounted as tmpfs with max size)

No comments: