释放Linux操作系统文件缓存


FROM :
http://pthread.blog.163.com/blog/static/1693081782011111402639863/
http://blog.itpub.net/26250550/viewspace-1200400/

修改/proc/sys/vm/drop_cache

  • 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

As this is a non-destructive operation, and dirty objects are not freeable, the user should run "sync" first in order to make sure all cached objects are freed.This tunable was added in 2.6.16.



无法修改 /proc/sys/vm/drop_cache

后来发现Linux的一个系统调用:
 #include
 int posix_fadvise(int fd, off_t offset, off_t len, int advice);
有一个选项POSIX_FADV_DONTNEED可以做这件事情


dcache.txt


使用方法:(gcc -o dhcache dhcache.c)
dcache -h
dcache is an utility to drop file cache.
usage:dcache [-s] file
        -s,--sync, sync data before drop cache.
        -h,--help, print help.

--sync选项用于将数据写回硬盘。因为man posix_fadvise说了:

 POSIX_FADV_DONTNEED  attempts  to  free  cached  pages  associated with the specified region.  This is useful, for  example, whilestreaming large files.  A program may periodically request the kernel to free cached data that has already  been  used,  so  that more useful cached pages are not discarded instead.

 Pages  that  have  not  yet  been  written  out  will be unaffected, so if the application wishes to guarantee that pages will be
 released, it should call fsync(2) or fdatasync(2) first.

说POSIX_FADV_DONTNEED只释放clean页面,dirty页面,并不受此影响,所以如果你是写了文件而没有用--sync选项的话,那么脏页面不会被释放,缓存也就不会被释放掉啦。所以使用dcache的时候应当清楚何时使用--sync选项。

在公司机器上做了一下实验,用一个4kw+行的文本文件,8GB做实验。

先 free -m看一下cached总数为48345M
             total       used       free     shared    buffers     cached
Mem:     64334    50469    13864          0        196      48345

然后wc -l 5kw.txt,读取一遍文件,wc输出文件行数为
44731963 5kw.txt

然后再free -m一遍看内存情况:
             total       used       free     shared    buffers     cached
Mem:     64334   58802     5532          0        204        56670
可以看到,cached page增加了8325M,与我们文件大小接近。然后使用dcache工具释放对应文件在系统中的缓存:

dcache 5kw.txt
drop cache of plsi_index.5kw.txt success.
再次使用free -m看到cached果然被释放了8GB,说明工具确实起到了作用。
 free -m
             total       used       free     shared    buffers     cached
Mem:    64334    50477      13856          0        204      48346
请使用浏览器的分享功能分享到微信等