細心的朋友會注意到,當你在linux下頻繁存取檔案後,實體記憶體會很快被用光,當程式結束後,記憶體不會被正常釋放,而是一直作為caching.這個問題,貌似有不少人在問,不過都沒有看到有什麼很好解決的辦法.那麼我來談談這個問題.
先來說說free指令
[root@server ~]# free -m
total used free shared buffers cached
Mem: 249 163 86 0 10 94
-/+ buffers/cache: 58 191
Swap: 511 0 511
其中:
total 記憶體總數
used 已經使用的記憶體數
free 空閑的記憶體數
shared 多個程序共享的記憶體總額
buffers Buffer Cache和cached Page Cache 磁盤緩存的大小
-buffers/cache 的記憶體數:used - buffers - cached
+buffers/cache 的記憶體數:free + buffers + cached
可用的memory=free memory+buffers+cached
有了這個基礎後,可以得知,我現在used為163MB,free為86,buffer和cached分别為10,94
那麼我們來看看,如果我執行複制檔案,記憶體會發生什麼變化.
[root@server ~]# cp -r /etc ~/test/
Mem: 249 244 4 0 8 174
-/+ buffers/cache: 62 187
在我指令執行結束後,used為244MB,free為4MB,buffers為8MB,cached為174MB,天呐都被cached吃掉了.别緊張,這是為了提高檔案讀取效率的做法.
引用[url]http://www.2qyou.com/thread-591-1-1.html[/url] 為了提高磁盤存取效率, Linux做了一些精心的設計, 除了對dentry進行緩存(用于VFS,加速檔案路徑名到inode的轉換), 還采取了兩種主要Cache方式:Buffer Cache和Page Cache。前者針對磁盤塊的讀寫,後者針對檔案inode的讀寫。這些Cache有效縮短了 I/O系統調用(比如read,write,getdents)的時間。"
那麼有人說過段時間,linux會自動釋放掉所用的記憶體,我們使用free再來試試,看看是否有釋放>?
[root@server test]# free -m
Mem: 249 244 5 0 8 174
-/+ buffers/cache: 61 188
MS沒有任何變化,那麼我能否手動釋放掉這些記憶體呢???回答是可以的!
/proc是一個虛拟檔案系統,我們可以通過對它的讀寫操作做為與kernel實體間進行通信的一種手段.也就是說可以通過修改/proc中的檔案,來對目前kernel的行為做出調整.那麼我們可以通過調整/proc/sys/vm/drop_caches來釋放記憶體.操作如下:
[root@server test]# cat /proc/sys/vm/drop_caches
0
首先,/proc/sys/vm/drop_caches的值,預設為0
[root@server test]# sync
手動執行sync指令(描述:sync 指令運作 sync 子例程。如果必須停止系統,則運作 sync 指令以確定檔案系統的完整性。sync 指令将所有未寫的系統緩沖區寫到磁盤中,包含已修改的 i-node、已延遲的塊 I/O 和讀寫映射檔案)
[root@server test]# echo 3 > /proc/sys/vm/drop_caches
3
将/proc/sys/vm/drop_caches值設為3
Mem: 249 66 182 0 0 11
-/+ buffers/cache: 55 194
再來運作free指令,發現現在的used為66MB,free為182MB,buffers為0MB,cached為11MB.那麼有效的釋放了buffer和cache.
有關/proc/sys/vm/drop_caches的用法在下面進行了說明
/proc/sys/vm/drop_caches (since Linux 2.6.16)
Writing to this file causes the kernel to drop clean caches,
dentries and inodes from memory, causing that memory to become
free.
To free pagecache, use echo 1 > /proc/sys/vm/drop_caches; to
free dentries and inodes, use echo 2 > /proc/sys/vm/drop_caches;
to free pagecache, dentries and inodes, use echo 3 >
/proc/sys/vm/drop_caches.
Because this is a non-destructive operation and dirty objects
本文轉自holy2009 51CTO部落格,原文連結:http://blog.51cto.com/holy2010/414341