释放swap

本文详细介绍了Linux系统中Swap空间的管理与优化方法,包括如何安全地关闭和启动Swap,以及调整swappiness参数来平衡物理内存与Swap的使用。同时,提供了增加Swap空间的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

释放swap
风险:
机器必须有足够多的物理内存,否则贸然swapon/swapoff会导致OOM随机kill掉进程从而出现问题;

The kernel attempts to remove all swap files/partitions that it currently has active.  To do this, it needs to move all the data that is stored in the swap files back into RAM.  Since a lot of RAM is often used for buffer cache, at least on Linux, trying to find space in RAM for the pages that were swapped out means flushing buffers and dumping disk cache, which may cause writes to disk.  Depending on how much the the space being used by disk buffers is dirty, it could take a while to turn off large amounts of swap space that is has significant portions of it used, because of the possibility of significant disk activity.
原理:
swapoff -a的时候,内核尝试删除处于活动状态的交换文件或分区,为此它需要将存储在交换文件中的所有数据移回RAM。 通常情况下,Linux上大量的RAM用于缓冲区缓存,Linux会尝试在RAM上查找已换出的页面空间,这意味着刷新缓冲区,并交换出磁盘缓存(写入硬盘)。这可能导致大量的IO;根据有交换分区的大小,可能需要一定时间才能关闭完交换空间;

所以建议操作前清理下缓存

除此之外没有其他影响;
操作:
step 1: 清除caches  PageCache, dentries 和 inodes.
sync; echo 3 > /proc/sys/vm/drop_caches 

step 2: 关闭交换分区
swapoff -a

step 3: 开启交换分区
swapon -a
 

[root@93a17e41-ee44-4c53-8432-b196632b8891 ~]# free -m
             total       used       free     shared    buffers     cached
Mem:        257545      78679     178866       3554         31       5203
-/+ buffers/cache:      73445     184100
Swap:        16383          0      16383

 

另:

Linux 根据swappiness的值来决定使用物理内存还是swap的趋势;值越小,越趋向于使用RAM,越大越趋向于使用swap;

修改方法:

及时生效:echo 10 >  /proc/sys/vm/swappiness
永久生效  编辑/etc/sysctl.conf,添加: "vm.swappiness = 10"

 

还有一种方法就是增加swap空间:

增加16G swap
dd if=/dev/zero of=/export/data/tmp/swap bs=16384 count=1048576
mkswap swap
swapon swap

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值