swap分区在系统的物理内存不够用时,把硬盘的一部分空间释放出来,以供当前运行的程序使用。(临时使用,如果swap分区都不够了还是直接加内存吧)
(1).步骤
mkswap /devices(可以是分区地址,也可以是文件) 格式化成swap分区
swapon /devices(可以是分区地址,也可以是文件) 激活/swap,加入到swap分区中
vim /etc/fstab(添加开机自动添加到swap分区),追加/devices swap swap defaults 0 0
(2).实际操作
通过分区扩展swap分区:
[root@xuexi ~]# fdisk /dev/sdb //新建一个分区
WARNING: fdisk GPT support is currently new, and therefore in an experimental phase. Use at your own discretion.
欢迎使用 fdisk (util-linux 2.23.2)。
更改将停留在内存中,直到您决定将更改写入磁盘。
使用写入命令前请三思。
命令(输入 m 获取帮助):n
分区号 (1-128,默认 1):
第一个扇区 (34-4194270,默认 2048):
Last sector, +sectors or +size{K,M,G,T,P} (2048-4194270,默认 4194270):+1G
已创建分区 1
命令(输入 m 获取帮助):w
The partition table has been altered!
Calling ioctl() to re-read partition table.
正在同步磁盘。
[root@xuexi ~]# mkswap /dev/sdb1 //格式化成swap分区
mkswap: /dev/sdb1: warning: wiping old xfs signature.
正在设置交换空间版本 1,大小 = 1048572 KiB
无标签,UUID=b99f3b95-35ba-4161-9c6c-a616665be0da
[root@xuexi ~]# free -m //查看
total used free shared buff/cache available
Mem: 1980 692 589 13 697 1062
Swap: 2047 0 2047
[root@xuexi ~]# swapon /dev/sdb1 //激活并加入到swap分区
[root@xuexi ~]# free -m
total used free shared buff/cache available
Mem: 1980 691 591 13 697 1063
Swap: 3071 0 3071
[root@xuexi ~]# swapoff /dev/sdb1 //关闭
[root@xuexi ~]# free -m
total used free shared buff/cache available
Mem: 1980 691 592 13 697 1064
Swap: 2047 0 2047
[root@xuexi ~]# swapon -s //查看swap分区里存在哪些分区或文件
文件名 类型 大小 已用 权限
/dev/sda2 partition 2097148 0 -2
[root@xuexi ~]#
通过文件扩展swap分区:
[root@xuexi ~]# dd if=/dev/zero of=swap_file bs=1M count=500 //创建一个500M的空文件
记录了500+0 的读入
记录了500+0 的写出
524288000字节(524 MB)已复制,3.68587 秒,142 MB/秒
[root@xuexi ~]# mkswap swap_file //格式化成swap
正在设置交换空间版本 1,大小 = 511996 KiB
无标签,UUID=ebb5b2ef-04b0-4632-9a5f-91ee1fb8a47f
[root@xuexi ~]# free -m //查看
total used free shared buff/cache available
Mem: 1980 696 139 13 1144 1051
Swap: 2047 0 2047
[root@xuexi ~]# swapon swap_file //激活并加入到swap分区
swapon: /root/swap_file:不安全的权限 0644,建议使用 0600。
[root@xuexi ~]# free -m //可以看到实际上已经添加了,报错只是权限问题
total used free shared buff/cache available
Mem: 1980 697 137 13 1145 1050
Swap: 2547 0 2547
[root@xuexi ~]# chmod 0600 swap_file //按照提示修改下权限