Unix-like · 2017-01-12 0

Linux 的缓存内存机制

在讲解Linux内存管理时已经提到,当你在Linux下频繁存取文件后,即使系统上没有运行许多程序,也会占用大量的物理内存。这是因为当你读写文件的时候,Linux内核为了提高读写的性能和速度,会将文件在内存中进行缓存,这部分内存就是Cache Memory(缓存内存)。即使你的程序运行结束后,Cache Memory 也不会自动释放,这就会导致你的Linux系统在频繁读写文件后,可用物理内存会很少。

可用 free 命令查看cache的大小:

[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——已使用内存,一般情况这个值会比较大,因为这个值包括了cache+应用程序使用的内存
    free——完全未被使用的内存
    shared——应用程序共享内存
    buffers——缓存,主要用于目录方面,inode值等(ls大目录可看到这个值增加)
    cached——缓存,用于已打开的文件
    总结:
    total=used+free
    used=buffers+cached (maybe add shared also)
  • 第二行描述应用程序的内存使用:
    前个值表示-buffers/cache——应用程序使用的内存大小,used减去缓存值
    后个值表示+buffers/cache——所有可供应用程序使用的内存大小,free加上缓存值
    总结:
    -buffers/cache=used-buffers-cached
    +buffers/cache=free+buffers+cached
  • 第三行表示swap分区的使用:
    used——已使用
    free——未使用

为了提高磁盘存取效率, Linux做了一些精心的设计, 除了对dentry进行缓存(用于VFS,加速文件路径名到inode的转换), 还采取了两种主要Cache方式:Buffer Cache和Page Cache。前者针对磁盘块的读写,后者针对文件 inode 的读写。这些Cache有效缩短了 I/O系统调用(比如read,write,getdents)的时间。

/proc
操作系统运行时,进程(正在运行中的程序)信息及内核信息(比如cpu、硬盘分区、内存信息等)存放在这里。/proc目录是伪装的文件系统proc的挂载目录,proc并不是真正的文件系统。因此,这个目录是一个虚拟的目录,它是系统内存的映射,我们可以通过直接访问这个目录来获取系统信息。也就是说,这个目录的内容不在硬盘上而是在内存里。

/proc是一个虚拟文件系统,我们可以通过对它的读写操作做为与kernel实体间进行通信的一种手段。也就是说可以通过修改/proc中的文件,来对当前kernel的行为做出调整。那么我们可以通过调整/proc/sys/vm/drop_caches来释放内存。操作如下:

scutech@scutech-zw:~$  cat /proc/sys/vm/drop_caches
0

/proc/sys/vm/drop_caches 的默认值为0,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:
* 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.

运行sync将dirty的内容写回硬盘:

scutech@scutech-zw:~$ sync

通过修改proc系统的drop_caches清理free的cache:

$echo 3 > /proc/sys/vm/drop_caches

个人经验认为没必要手动释放,这种内存管理方式也是比Windows优胜的地方之一。因为Linux的内核内存管理机制,一般情况下不需要特意去释放已经使用的cache。这些cache起来的内容可以提高文件以及磁盘的读写速度。