Welcome to Rooeye's blog

释放linux服务器的内存

linux JInkun 1984℃ 0评论

服务器内存大小为2G,今早起来用free命令查看空余内存大小发现只剩下 60多M,顿时很紧张,吃完早饭来到图书馆后,重新查看服务器空余内存,发现竟然变成600多M,很纳闷,应该变得更小才对,咋还变大了呢?


通过查阅资料发现,linux服务器会在其内存不足的情况下自动释放缓存(Cache)区域,增大空余内存(free)。先来看free命令各个结果的含义:



total: 内存总大小
used: 已使用了的内存大小
free :  完全未被使用的内存大小
shared:应用程序共享内存
buffers:  缓存,主要用于目录方面,inode值等
cached:  缓存,主要用于已经打开的文件
-buffers/cache:  应用程序真实使用的内存大小 -buffers/cache的值 = used -buffers – cached
+buffers/cache:  应用程序真实还可以利用的内存大小  +buffers/cache的值 = free + buffers + cached

上述值的公式关系如下:
total = used + free
total = (-buffers/cache的值) + ( +buffers/cache的值 )
-buffers/cache的值 = used -buffers – cached
+buffers/cache的值 = free + buffers + cached

所以当我们碰到linux服务器内存不足的时候,会自动释放缓存,增大free空间,完全不必紧张。

那么如果非想要立刻释放缓存而不是等待服务器自动释放呢?

操作步骤如下:

1. free -m 查看当前内存的使用情况



2. sync  将缓冲区的内容全部写入到磁盘中



3. 修改 /proc/sys/vm/drop_caches 文件内容,其内容由0变为3,或者使用 echo 3 > /proc/sys/vm/drop_caches 命令
/proc是一个虚拟文件系统,是用户访问系统内核数据的接口,可以通过更改该文件系统达到更改kernel行为的目的。
而  /proc/sys/vm/drop_caches 文件的官方解释如下:
Writing to this file causes the kernel to drop clean caches,dentries and inodes from memory, causing that memory   to becomefree.
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.

综上,就实现了手动释放缓存的效果,从而增大了空余内存。不过这么做其实也是没有必要的,因为linux服务器会在free变小的时候自动释放缓存。









来自为知笔记(Wiz)

转载请注明:晋坤 的博客 » 释放linux服务器的内存

喜欢 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址