Drop Caches

来源:互联网 发布:淘宝网广场舞服装扇子 编辑:程序博客网 时间:2024/05/29 14:22

Kernels 2.6.16 and newer provide a mechanism to have the kernel drop the page cache and/or inode and dentry caches on command, which can help free up a lot of memory. Now you can throw away that script that allocated a ton of memory just to get rid of the cache...

To use /proc/sys/vm/drop_caches, just echo a number to it.

To free pagecache:

# echo 1 > /proc/sys/vm/drop_caches

To free dentries and inodes:

# echo 2 > /proc/sys/vm/drop_caches

To free pagecache, dentries and inodes:

echo 3 > /proc/sys/vm/drop_caches

This is a non-destructive operation and will only free things that are completely unused. Dirty objects will continue to be in use until written out to disk and are not freeable. If you run "sync" first to flush them out to disk, these drop operations will tend to free more memory.

 

 

-----------------------------------------------------------------------------------------------------------------------------------------

     LINUX的内存管理机制,一般情况下不需要特意去释放已经使用的cache。Cache机制的存在,使得Linux对磁盘的读写速度是有较大的好处的。在 Linux 操作系统中,当应用程序需要读取文件中的数据时,操作系统先分配一些内存,将数据从存储设备读入到这些内存中,然后再将数据分发给应用程序;当需要往文件中写数据时,操作系统先分配内存接收用户数据,然后再将数据从内存写到磁盘上。
     写了个可释放Cached内存的Shell脚本,分享一下:

修改/etc/sysctl.conf 添加如下选项后就不会内存持续增加
vm.dirty_ratio = 1
vm.dirty_background_ratio=1
vm.dirty_writeback_centisecs=2
vm.dirty_expire_centisecs=3
vm.drop_caches=3
vm.swappiness =100
vm.vfs_cache_pressure=163
vm.overcommit_memory=2
vm.lowmem_reserve_ratio=32 32 8
kern.maxvnodes=3

上面的设置比较粗暴,使cache的作用基本无法发挥。需要根据机器的状况进行适当的调节寻找最佳的折衷。

#! /bin/bash
#Free的Memory小于400M时 释放Cached的内存
freemem=$(cat /proc/meminfo | grep "MemFree" | awk '{print $2}')
if [ $freemem -le 409600 ];then
    date  >> /var/log/mem.log
    free -m >> /var/log/mem.log
    sync
    sync
    echo 3 > /proc/sys/vm/drop_caches
    free -m >> /var/log/mem.log           
fi

# cache释放:
# To free pagecache:
# echo 1 > /proc/sys/vm/drop_caches
# To free dentries and inodes:
# echo 2 > /proc/sys/vm/drop_caches
# To free pagecache, dentries and inodes:
# echo 3 > /proc/sys/vm/drop_caches
# 说明,释放前最好sync一下,防止丢数据。

 

 

原创粉丝点击