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 //按照提示修改下權限