Linux自动释放内存脚本
在root目录下建立cache.sh文件:
1: vim cache.sh
#! /bin/bash
#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
释放内存之前,最好 sync 同步一下,方式数据丢失;
2: 添加可执行的权限
chmod +x cache.sh
3: 定时执行 crontab -e
*/2 * * * * sh /root/cache.sh
每 2 分钟执行一次;
4: 另一个脚本
#! /bin/sh
used=`free -m | awk 'NR==2' | awk '{print $3}'`
free=`free -m | awk 'NR==2' | awk '{print $4}'`
echo "===========================" >> /app/memory/logs/mem.log
date >> /app/memory/logs/mem.log
echo "Memory usage before | [Use:${used}MB][Free:${free}MB]" >> /app/memory/logs/mem.log
if [ $free -le 4000 ] ; then
sync && echo 1 > /proc/sys/vm/drop_caches
sync && echo 2 > /proc/sys/vm/drop_caches
sync && echo 3 > /proc/sys/vm/drop_caches
used_ok=`free -m | awk 'NR==2' | awk '{print $3}'`
free_ok=`free -m | awk 'NR==2' | awk '{print $4}'`
echo "Memory usage after | [Use:${used_ok}MB][Free:${free_ok}MB]" >> /app/memory/logs/mem.log
echo "OK" >> /app/memory/logs/mem.log
else
echo "Not required" >> /app/memory/logs/mem.log
fi
exit 1