linux清除cache的方法


1  Linux下內存占用多的原因

當linux第一次讀取一個文件運行時,一份放到一片內存中cache起來,另一份放入運行程序的內存中,正常運行,當程序運行完,關閉了,cache中的那一分卻沒有釋放,第二次運行的時候,系統先看看在內存中是否有一地次運行時存起來的cache中的副本,如果有的話,直接從內存中讀取,那樣,速度就快多了。

說明這種情況的很典型的例子是啟動firefox,由於firefox程序很大,因此第一次讀取運行的時候很慢,尤其在速度不快的機器上,但是當你徹底關閉了firefox,ps看不到一個firefox進程,第二次再啟動的時候就比第一次明顯快很多,這是由於這次系統是直接從cache中讀取的firefox來運行,並不是從磁盤上讀取的。

再有一個例子:我們頻繁使用的ls命令等基本命令,你運行的時候根本看不到硬盤燈閃,因為這些常用的命令都是再第一次運行后就保存在cache中的,以后就一直從內存中讀出來運行。

如果cache占用的內存過多了,影響正常運行程序需要的內存,那么會釋放掉一部分cache內存,但是總量會保持一個很高的值,所以,linux總是能最大限度的使用內存,就算加到16G,32G內存,也會隨着不斷的IO操作,內存的free值會慢慢減少到只有幾M,想要內存不發生這種情況,只有一個辦法:把內存加到比硬盤大。

2 手動釋放方法

2.1 使用free查看一下當前內存使用情況(可略過):

[root@*** ~]# free -m
total       used       free     shared    buffers     cached
Mem:           512        488         23          0         57        157
-/+ buffers/cache:        273        238 Swap:         1055          0       1055

2.2 執行sync同步數據

[root@*** ~]# sync

2.3 清理cache

[root@*** ~]#echo 3 > /proc/sys/vm/drop_caches

2.4 drop_cache的詳細文檔如下,以便查閱

Writing to this will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.
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
As this is a non-destructive operation, and dirty objects are notfreeable, the user should run "sync" first in order to make sure allcached objects are freed.
This tunable was added in 2.6.16.

 

網上查了查資料,整理一下:

關於drop_caches文件:系統默認為0

 

在Documentation/sysctl/vm.txt中有如下描述:

drop_caches

Writing to this will cause the kernel to drop clean caches, dentries and inodes from memory, causing that memory to become free.

To free pagecache:僅清除頁面緩存(PageCache)
 echo 1 > /proc/sys/vm/drop_caches

To free dentries and inodes:清除目錄項和inode
 echo 2 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:清除頁面緩存,目錄項和inode
 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.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM