内存泄露的查看与检测:
Linux Free 命令的输出:
total used free shared buffers cached
Mem: 8298904 6202940 2095964 0 400124 5291536
-/+ buffers/cache: 511280 7787624
Swap: 2048276 0 2048276
buffers 和 cached 主要是为了提高磁盘的读取效率,除了对dentry进行缓存外,还采取了两种cache方式:Buffer Cache和Page Cache,前者主要针对磁盘块的读写,后者主要针对inode的读写;
buffers 主要指Buffer Cache,cached 主要指Page Cache。
-/+ buffers/cache: 意思是减去(buffers + cached)后真正地内存使用量,和加上(buffers + cached)后真正地内存空闲量。
used数值包括了进城所使用的内存和一部分磁盘缓存;
那used的数值比较异常,是发生了内存泄露吗?非也!!
Usually the kernel handles memory utilization pretty well it caches memory for dentry cache, page cache and inodes which improves IO speed and performance generally. But in some cases user applications needs lots of memory and we need to clear what’s called dirty memory which could be inodes already written to the disk, so now the kernel given us the option to manage this manually. Used memory 几乎总是会包含磁盘缓存,所以文件读写过多之后导致可用内存就会急剧下降,其他应用需要内存的时候就会发生disk buffer的sync操作,以至于系统性能大受影响。
Linux Kernel提供了有效地方法来清除磁盘缓存:/proc/sys/vm/drop_caches (具体在哪个版本后的kernel才支持,尚未查阅)
echo 1 > /proc/sys/vm/drop_caches free page cache
echo 2 > /proc/sys/vm/drop_caches free dentry and inodes cache
echo 3 > /proc/sys/vm/drop_caches free both of the two above
在执行这些操作之前,最好先执行sync (flush file system buffers)
Linux principals:
When extra physical memory is not in use, the kernel attempts to put it to work as a disk buffer cache. The disk buffer stores recently accessed disk data in memory; if the same data is needed again it can be quickly retrieved from the cache, improving performance. The buffer grows and shrinks dynamically to use the memory available, although priority is given to using the memory for paging. Thus, all the memory you have is put to good use.