手工清除linux中的記憶體

myownstars發表於2011-02-24

 

首先檢視記憶體使用狀況
[root@testdb mysql]# free -m -t
             total       used       free     shared    buffers     cached
Mem:         15653      15596         56          0         14      11142
-/+ buffers/cache:       4439      11213
Swap:        31996       1901      30094
Total:       47650      17498      30151

/proc是一個虛擬檔案系統,我們可以透過對它的讀寫操作做為與kernel實體間進行通訊的一種手段。也就是說可以透過修改/proc中的檔案,來對當前kernel的行為做出調整。那麼我們可以透過調整/proc/sys/vm/drop_caches來釋放記憶體。操作如下:

[root@testdb2 init.d]# cat /proc/sys/vm/drop_caches
0
[root@testdb2 init.d]# echo 3 > /proc/sys/vm/drop_caches
將其設定為3
[root@testdb2 init.d]# cat /proc/sys/vm/drop_caches
3

[root@testdb mysql]# free -m -t
             total       used       free     shared    buffers     cached
Mem:         15653      12072       3581          0          1       7702
-/+ buffers/cache:       4368      11285
Swap:        31996       1900      30096
Total:       47650      13972      33677

/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
are not freeable, the user should run sync first.

1、從man可以看到,這值從2.6.16以後的核心版本才提供,也就是老版的作業系統,如紅旗DC 5.0、RHEL 4.x之前的版本都沒有;
2、若對於系統記憶體是否夠用的觀察,我還是原意去看swap的使用率和si/so兩個值的大小;
使用者常見的疑問是,為什麼free這麼小,是否關閉應用後記憶體沒有釋放?
但實際上,我們都知道這是因為Linux對記憶體的管理與Windows不同,free小並不是說記憶體不夠用了,應該看的是free的第二行最後一個值:
這才是系統可用的記憶體大小。
實際專案中告訴我們,如果因為是應用有像記憶體洩露、溢位的問題,從swap的使用情況是可以比較快速可以判斷的,但free上面反而比較難檢視。
相反,如果在這個時候,我們告訴使用者,修改系統的一個值,“可以”釋放記憶體,free就大了。使用者會怎麼想?不會覺得作業系統“有問題”嗎?
所以說,我覺得既然核心是可以快速清空buffer或cache,也不難做到(這從上面的操作中可以明顯看到),但核心並沒有這樣做(預設值是0),我們就不應該隨便去改變它。
一般情況下,應用在系統上穩定執行了,free值也會保持在一個穩定值的,雖然看上去可能比較小。
當發生記憶體不足、應用獲取不到可用記憶體、OOM錯誤等問題時,還是更應該去分析應用方面的原因,如使用者量太大導致記憶體不足、發生應用記憶體溢位等情況,否則,清空buffer,強制騰出free的大小,可能只是把問題給暫時遮蔽了。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/15480802/viewspace-687879/,如需轉載,請註明出處,否則將追究法律責任。

相關文章