手动释放Linux系统的内存

先来看看 CentOS 8 系统中 free 命令的输出。当然,它只是用来查看系统内存使用情况的,并非用来释放的。

# free -mh
              total        used        free      shared  buff/cache   available
Mem:          821Mi       204Mi        97Mi        10Mi       519Mi       465Mi
Swap:            0B          0B          0B

free 命令显示了系统中空闲的和使用了的所有的物理内存和交换(swap)内存,包括被kernel使用的 buffers 和 cache.
详细信息存储在 /proc/meminfo 中。
free 命令输出的各列含义如下:

total     安装的内存总量 (MemTotal and SwapTotal in /proc/meminfo)
used      使用掉的内存量 (total - free - buffers - cache)
free      没有使用的内存量 (MemFree + SwapFree in /proc/meminfo)
shared    Memory used (mostly) by tmpfs (Shmem in /proc/meminfo)
buffers   Memory used by kernel buffers (Buffers in /proc/meminfo)
cache     Memory used by the page cache and slabs (Cached and SReclaimable in /proc/meminfo)
buff/cache
       Sum of buffers and cache
available
       如果新起应用程序,那么有多少内存可供使用,不包括交换内存(swap)。
       Unlike the data provided  by  the  cache  or free  fields,  
       this  field  takes  into account page cache and also that not all reclaimable memory slabs 
       will be reclaimed due to items being in use 
       (MemAvailable in /proc/meminfo, available on kernels 3.14, emulated on kernels 2.6.27+, otherwise the same as free)

由以上可知:

  1. total = used + free + buff/cache
  2. buff/cache = kernel buffers + page cache + slabs
  3. total - used = free + buff/cache > available

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

那么,如果希望手动释放buffer cache和page cache所占用的内存,应该怎么做呢?

第一步,运行 sync 命令。
sync 命令将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-node、已延迟的块 I/O 和读写映射文件。

第二步,写内存文件 /proc/sys/vm/drop_caches

# 释放 page cache
echo 1 > /proc/sys/vm/drop_caches

# 释放 dentries and inodes
echo 2 > /proc/sys/vm/drop_caches

# 释放 page cache, dentries and inodes
echo 3 > /proc/sys/vm/drop_caches

该文件内容默认为0. 以上3种写入方法,择一即可。
之后,立即再运行free命令,即可看到 buff/caches 变得比原来小很多了。

# free -mh
              total        used        free      shared  buff/cache   available
Mem:          821Mi       161Mi       534Mi        20Mi       125Mi       524Mi
Swap:            0B          0B          0B

(完)

发布了169 篇原创文章 · 获赞 332 · 访问量 48万+

猜你喜欢

转载自blog.csdn.net/nirendao/article/details/104097617