副标题#e#
一个经常被问到的 Linux 问题:为啥 Linux 系统没运行多少程序,显示的可用内存这么少?
其实 Linux 与 Windows 的内存管理不同,会尽量缓存内存以提高读写性能,通常叫做 Cache Memory。
比较老的资料都会介绍 Linux 的 Cache 占用很多并没有关系,因为 Linux 会尽可能利用内存进行缓存。但是缓存的回收也是需要资源的,比较好的一篇文章是 Poor Zorro 写的 Linux 内存中的 Cache 真的能被回收么?。
虽然大部分情况下我们看到 Cache 占用很高时是没有问题的,但是我们还是想弄清楚到底是哪个程序把 Cache 弄的那么高,这居然不是一件容易的事。
内核的模块在分配资源的时候,为了提高效率和资源的利用率,都是透过 Slab 来分配的。Slab 为结构性缓存占用内存,该项也经常占用很大的内存。不过借助 slabtop 工具,我们可以很方便的显示内核片缓存信息,该工具可以更直观的显示 /proc/slabinfo 下的内容。
# 显示了一台机器缓存中占用对象的情况
$ slabtop -s c
Active / Total Objects (% used) : 856448 / 873737 (98.0%)
Active / Total Slabs (% used) : 19737 / 19737 (100.0%)
Active / Total Caches (% used) : 67 / 89 (75.3%)
Active / Total Size (% used) : 141806.80K / 145931.33K (97.2%)
Minimum / Average / Maximum Object : 0.01K / 0.17K / 8.00K
OBJS ACTIVE USE OBJ SIZE SLABS OBJ/SLAB CACHE SIZE NAME
416949 416949 100% 0.10K 10691 39 42764K buffer_head
5616 5545 98% 2.00K 351 16 11232K kmalloc-2048
9114 8990 98% 1.02K 294 31 9408K ext4_inode_cache
12404 12404 100% 0.57K 443 28 7088K radix_tree_node
10800 10731 99% 0.58K 400 27 6400K inode_cache
31290 29649 94% 0.19K 745 42 5960K dentry
3552 3362 94% 1.00K 111 32 3552K kmalloc-1024
1100 1055 95% 2.84K 100 11 3200K task_struct
1649 1481 89% 1.88K 97 17 3104K TCP
27000 27000 100% 0.11K 750 36 3000K sysfs_dir_cache
1380 1269 91% 2.06K 92 15 2944K sighand_cache
虽然上面的命令显示了 Cache 中 Slab 的情况,但是还是没有显示什么程序占用的 Cache。
方案一:使用 Pcstat 来实现
经过搜索,发现 linux-ftools 这个工具可以显示某个文件占用的 Cache 的情况, fincore 只是它其中的一个工具。
$ fincore [options] files...
--pages=false Do not print pages
--summarize When comparing multiple files, print a summary report
--only-cached Only print stats for files that are actually in cache.
#p#副标题#e#
stats for CLUSTER_LOG_2010_05_22.MYI: file size=417792 , total pages=102 , cached pages=1 , cached size=4096, cached perc=0.980392
stats for CLUSTER_LOG_2010_05_23.MYI: file size=826368 , total pages=201 , cached pages=1 , cached size=4096, cached perc=0.497512
#p#分页标题#e#
stats for CLUSTER_LOG_2010_05_24.MYI: file size=192512 , total pages=47 , cached pages=1 , cached size=4096, cached perc=2.127660
stats for CLUSTER_LOG_2010_06_03.MYI: file size=345088 , total pages=84 , cached pages=43 , cached size=176128, cached perc=51.190476
stats for CLUSTER_LOG_2010_06_04.MYD: file size=1478552 , total pages=360 , cached pages=97 , cached size=397312, cached perc=26.944444
stats for CLUSTER_LOG_2010_06_04.MYI: file size=205824 , total pages=50 , cached pages=29 , cached size=118784, cached perc=58.000000
stats for COMMENT_CONTENT_2010_06_03.MYI: file size=100051968 , total pages=24426 , cached pages=10253 , cached size=41996288, cached perc=41.975764
stats for COMMENT_CONTENT_2010_06_04.MYD: file size=716369644 , total pages=174894 , cached pages=79821 , cached size=326946816, cached perc=45.639645