日期:2014-05-16  浏览次数:20635 次

Linux内置命令free的输出详解
背景:
        最近协助QA测试自己开发的server模块,压测下观察进程内存使用情况时,用到了linux系统内置指令free,不得不说,对于Linux新手来说,这个指令的输出结果可能让人摸不着头脑。
        为搞清出其输出含义,查了一些资料,作为笔记,记录于此,也希望能帮助到同样疑惑的新手。

实例:

        在运行server进程的机器命令行输入:free -m // Note: -m 指定输出数据以megabytes为单位进行显示
        输出结果如下:
                        total          used         free     shared    buffers     cached
    Mem:         15360      13465       1894             0           45         9962
    -/+ buffers/cache:         3456     11903
    Swap:                 0               0              0
    当我看到这个输出时,比较茫然,大体来说,有3个主要疑问:
        疑惑点1. 15G内存的机器,为何free memory只有1894M ? 剩余的跑到哪里去了?
        疑惑点2.  buffers和cached是什么意思?
        疑惑点3.  -/+ buffers/cache是什么意思?该行输出的那两列数据是怎么计算出来的?数值表示的到底是什么?    

    不知所措?这时候,google该出手啦!

    一番折腾,站在众多大牛的肩膀上,现在终于搞明白了。

调研资料:

      1. 首先要对linux存储管理有一定理解,下面的链接可以提供帮助(之前有操作系统基础的话,更容易理解)
        关于linux kernel对机器内存的使用:
        http://serverfault.com/questions/9442/why-does-red-hat-linux-report-less-free-memory-on-the-system-than-is-actually-av
        大概意思就是,linux要最大程度地压榨机器资源,所以即使机器刚启动,其free memory也比预期的少很多,原因是操作系统把大部分的memory预先reserve起来,后续的内存分配由OS负责在这些reserved memory中进行调度或重分配
       至此,第1个疑问有了答案
    2. 关于buffers和cached的概念:
       http://stackoverflow.com/questions/6345020/linux-memory-buffer-vs-cache

       很多术语翻译过来感觉不地道,所以建议直接看原帖的英文解释

       至此,第2个疑问亦有了答案

    3. 内置命令free输出-/+ buffers/cache行的含义
       http://thoughtsbyclayg.blogspot.com/2008/09/display-free-memory-on-linux-ubuntu.html
       最重要的一段摘出如下:
       So really the buffers would be allocated to a running process if it asked for them anyway, and the memory being used to cache copies of recently used files would be released immediately if it makes sense to allocate the RAM elsewhere. So all that memory is 'available'. 
       Using these definitions:
       When thinking about 'how much memory is really being used' - I want to calculate:
          'used' - ('buffers' + 'cached')
       When thinking about 'how much memory is really free' - I want to calculate:
          'free' + ('buffers' + 'cached')

       With this in mind, the meaning of the second row header form the output of the Linux command "free" (-/+ buffers/cache:) makes more sense...

       至此,第3个疑问也解决了

结果分析: