Sunday, February 15, 2015

Clearing memory buffers and caches in linux



Sync : 

Sync command creates a system call to kernel to flushes  disk caches in memory to the filesystems

(Both internal and external hard drives).It is similar to umount command which also flushes the caches but umount also unmounts which may not suitable for online operations.

Eg ) You have memory intensive applications open but need to poweroff the system immediately , then sync command is a crude way to help you commit changes from memory to disk without closing the applications and waiting for them to close.

Also many modern disk drive devices have write caching enabled , which cache write operations and commit the changes in bulk for throughput and power saving reasons.

Sync command has to be run as root.

#sync

Freeing  memory buffers.

Generally kernel periodically writes dirty pages to disk and manually emptying memory might slow down performance as data might be needed to read from slow disks when accessed again.
But in a server environment , where we suspect memory leaks (With long uptime ) or a need to bring down ,we can use below approach.
 We can use below command as root to free pages cached in memory , note that they will be simply discarded and we may lose data ,hence it is recommended to be used along with sync command in an atomic operation.

echo 3 > /proc/sys/vm/drop_caches

Recommended:

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

The default value for the kernel parameters in most system is 0 which means pages (containing files and data)
will be cached in main memory



As per kernel.org , echo 3 applies for pages and other objects while echo 1 applies only for pages and echo2 for dentries and inodes .

To free pagecache:
 echo 1 > /proc/sys/vm/drop_caches
To free reclaimable slab objects (includes dentries and inodes):
 echo 2 > /proc/sys/vm/drop_caches
To free slab objects and pagecache:
 echo 3 > /proc/sys/vm/drop_caches

Dentry - Directry entries which maps file names to inodes of files , and also maps  to the filesystem hierarchy like parent and child directories.

Inode - Index nodes.In linux ,the file is identified by a number called inode. The inode also stores the groups and permisssions of a file.






No comments:

Post a Comment