Linux交换分区修改
参考:https://www.baeldung.com/linux/increase-swap-space
显示当前交换分区大小
swapon --show
显示为空则表示没有交换分区
swap 扩容
btrfs 文件系统
参考:https://unix.stackexchange.com/questions/599949/swapfile-swapon-invalid-argument
使用如下命令创建对应的 swap 文件,否则出现错误swapon: /home/swap_extend: swapon failed: Invalid argument
。仅替换增加交换分区部分。
sudo btrfs filesystem mkswapfile --size 16g --uuid clear /path/to/swap_extend
- 增加交换分区
sudo fallocate -l 8G /path/to/swap_extend
# or
sudo dd if=/dev/zeo of=/path/to/swap_extend bs=1G count=8
使用 dd
速度比较慢
- 改变 swap 权限
sudo chmod 600 /path/to/swap_extend
- 创建 swap 分区
sudo mkswap /path/to/swap_extend
- 开启 swap 分区
sudo swapon /path/to/swap_extend
为了确保开机启动生效,编辑/etc/fstab
,加入新创建的swap_extend
文件
/path/to/swap_extend none swap sw 0 0
确保挂载顺序正确
一个示例如下:
/dev/sda2 /home btrfs defaults,noatime 0 1
/home/swap_extend none swap sw 0 0
- 确认
$ swapon --show
NAME TYPE SIZE USED PRIO
/dev/nvme0n1p2 partition 4G 546M -2
/home/swap_extend file 16G 64.4M -3
查看当前内存状态
$ free -h
total used free shared buff/cache available
Mem: 15Gi 4.5Gi 7.2Gi 36Mi 4.1Gi 10Gi
Swap: 19Gi 609Mi 19Gi
移除交换分区
- 停止 swap
swapoff -v /path/to/swap_extend
- 修改
/etc/fstab
移除/path/to/swap_extend none swap swap defaults 0 0
- 删除 swapfile 文件
sudo rm /path/to/swap_extend
我的系统上并不能生效,即/etc/fstab
中/home/swap_extend
并未生效,因此采用openrc
进行管理
创建/etc/init.d/late_swap
:
#!/sbin/openrc-run
# Copyright 2025 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
name="late_swap daemon"
description="Enable swap file in /home after /home is mounted"
command=/usr/bin/late_swap
command_args="${late_swap_args}"
depend() {
need localmount
after localmount
}
start() {
ebegin "Enabling late swap file"
swapon /home/swap_extend
eend $?
}
添加到默认启动
sudo rc-update add late_swap default
comment:
- Valine
- LiveRe
- ChangYan