Linux-手动释放linux内存cache

来源:互联网 发布:mac 开机密码设置 编辑:程序博客网 时间:2024/05/28 04:52

操作

执行以下命令

 [root@entel2 ~]# sync    [root@entel2 ~]# echo 3 > /proc/sys/vm/drop_caches

重新查询

这里写图片描述


探究

free的用法

[root@entel2 rh]# free -helpfree: invalid option -- 'h'usage: free [-b|-k|-m|-g] [-l] [-o] [-t] [-s delay] [-c count] [-V]  -b,-k,-m,-g show output in bytes, KB, MB, or GB  -l show detailed low and high memory statistics  -o use old format (no -/+buffers/cache line)  -t display total for RAM + swap  -s update every [delay] seconds  -c update [count] times  -V display version information and exit

以M为单位显示内存

这里写图片描述

我们先来探究一下参数含义

  • total 内存总数
  • used 已经使用的内存数
  • free 空闲的内存数
  • shared 多个进程共享的内存总额
  • buffers Buffer Cache和cached Page Cache 磁盘缓存的大小
  • -buffers/cache (已用)的内存数:used - buffers - cached
  • +buffers/cache(可用)的内存数:free + buffers + cached
  • 可用的memory=free memory+buffers+cached

当在Linux下频繁存取文件后,物理内存会很快被用光,当程序结束后,内存不会被正常释放,而是一直作为caching。

手动释放缓存

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

那么我们可以通过调整/proc/sys/vm/drop_caches来释放内存。操作如下:

# cat /proc/sys/vm/drop_caches0

首先,/proc/sys/vm/drop_caches的值,默认为0。

# sync

手动执行sync命令(描述:sync 命令运行 sync 子例程。如果必须停止系统,则运行sync 命令以确保文件系统的完整性。sync 命令将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-node、已延迟的块 I/O 和读写映射文件)

# echo 3 > /proc/sys/vm/drop_caches# cat /proc/sys/vm/drop_caches3

将/proc/sys/vm/drop_caches值设为3


/proc/sys/vm/drop_caches用法

/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


意见总结

从man可以看到,这值从2.6.16以后的核心版本才提供,也就是老版的操作系统,如红旗DC 5.0、RHEL 4.x之前的版本都没有;若对于系统内存是否够用的观察,我还是原意去看swap的使用率和si/so两个值的大小;

用户常见的疑问是,为什么free这么小,是否关闭应用后内存没有释放?但实际上,我们都知道这是因为Linux对内存的管理与Windows不同,free小并不是说内存不够用了,应该看的是free的第二行最后一个值:-/+ buffers/cache: 58 191,这才是系统可用的内存大小。

实际项目中告诉我们,如果因为是应用有像内存泄露、溢出的问题,从swap的使用情况是可以比较快速可以判断的,但free上面反而比较难查看。

一般情况下,应用在系统上稳定运行了,free值也会保持在一个稳定值的,虽然看上去可能比较小。

当发生内存不足、应用获取不到可用内存、OOM错误等问题时,还是更应该去分析应用方面的原因,如用户量太大导致内存不足、发生应用内存溢出等情况,否则,清空buffer,强制腾出free的大小,可能只是把问题给暂时屏蔽了。

我觉得,排除内存不足的情况外,除非是在软件开发阶段,需要临时清掉buffer,以判断应用的内存使用情况;或应用已经不再提供支持,即使应用对内存的时候确实有问题,而且无法避免的情况下,才考虑定时清空buffer。(可惜,这样的应用通常都是运行在老的操作系统版本上,上面的操作也解决不了)。而生产环境下的服务器可以不考虑手工释放内存,这样会带来更多的问题。记住内存是拿来用的,不是拿来看的。

我们看linux,只要不用swap的交换空间,就不用担心自己的内存太少。如果常常swap用很多,可能你就要考虑加物理内存了,这也是linux看内存是否够用的标准.

1 0
原创粉丝点击