Linux下swap(交換分割槽)的增刪改

上古南城發表於2022-03-25

swap介紹

Linux 的交換分割槽(swap),或者叫記憶體置換空間(swap space),是磁碟上的一塊區域,可以是一個分割槽,也可以是一個檔案,或者是他們的組合。交換分割槽的作用是,當系統實體記憶體吃緊時,Linux 會將記憶體中不常訪問的資料儲存到swap 上,這樣系統就有更多的實體記憶體為各個程式服務,而當系統需要訪問 swap 上儲存的內容時,再將 swap 上的資料載入到記憶體中,也就是說,當正常記憶體已經佔滿,不夠用時,系統就會使用虛擬記憶體,以緩解伺服器壓力,避免崩潰,增強穩定性。但是其速度有限,常只是作為突發情況的緩衝。

使用 swap 交換分割槽,顯著的優點是,通過作業系統的排程,應用程式實際可以使用的記憶體空間將遠遠超過系統的實體記憶體。由於硬碟空間的價格遠比 RAM 要低,因此這種方式無疑是經濟實惠的。當然,頻繁地讀寫硬碟,會顯著降低作業系統的執行速率,這也是使用 swap 交換分割槽最大的限制。

使用 swap 必須要知道它存在的缺點,以便判斷何時使用交換分割槽。使用交換分割槽的好處當然就是可以一定程度的緩解記憶體空間緊張的問題。然而,由於 CPU 所讀取的資料都來自於記憶體,交換分割槽則是存放在磁碟上的,磁碟的速度和記憶體比較起來慢了好幾個數量級,如果不停的讀寫 swap,那麼對系統的效能肯定有影響,尤其是當系統記憶體很吃緊的時候,讀寫 swap 空間發生的頻率會很高,導致系統執行很慢。

如果使用是桌面系統,由於系統會自動將不常用的記憶體資料移到 swap 上,對桌面程式來說,有可能會導致最小化一個程式後,再開啟時小卡一下,因為需要將 swap 上的資料重新載入到記憶體中來。在部署了資料庫的系統上,也不建議用交換分割槽,因為頻繁地在記憶體和磁碟上相互導資料會影響資料庫效能。

很多時候我們安裝系統的時候並沒有考慮到,並不會劃分swap分割槽,而當需要用到時,可以通過命令手動增加,刪除,修改swap虛擬記憶體。下面就詳細記錄介紹一下如何操作虛擬記憶體。

新增swap有兩種方式:

  • 磁碟上新增一個分割槽(lvm分割槽或直接分割槽),用分割槽作為swap。
  • 磁碟上新增一個固定大小的檔案,用檔案作為swap。

推薦: 使用分割槽方式,新增一個分割槽。分割槽型別fdisk下為82,gdisk下為8200,partep分割槽標記沒有定義swap,其實分割槽後不更改分割槽型別也行測試也可以用,但為了在分割槽工具下方便檢視最好還是把分割槽型別改成swap對應的分割槽型別,本人理解分割槽型別就是分割槽軟體下用來描述分割槽所要承載的檔案系統的型別,比如分割槽型別為83表示為linxu分割槽,用於格式化成ext3 ext4等linux檔案系統,分割槽建立的方法這裡就不寫了前面有分割槽建立的方法。

 準備環境

[root@localhost ~]# cat /etc/redhat-release 
CentOS Linux release 7.5.1804 (Core) 
[root@localhost ~]# uname -r
3.10.0-862.el7.x86_64
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         121        3474          11         338        3545
Swap:             0           0           0
[root@localhost ~]# df -Th
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/sda2      xfs        19G  1.1G   18G   6% /
devtmpfs       devtmpfs  2.0G     0  2.0G   0% /dev
tmpfs          tmpfs     2.0G     0  2.0G   0% /dev/shm
tmpfs          tmpfs     2.0G   12M  2.0G   1% /run
tmpfs          tmpfs     2.0G     0  2.0G   0% /sys/fs/cgroup
/dev/sda1      xfs       297M  107M  191M  36% /boot
tmpfs          tmpfs     394M     0  394M   0% /run/user/0
[root@localhost ~]# blkid
/dev/sda1: UUID="0705b568-de2f-40dc-940f-ea2c91b3f059" TYPE="xfs" 
/dev/sda2: UUID="57859f61-6df4-40dc-8da5-6998dc7df3a7" TYPE="xfs" 
/dev/sr0: UUID="2018-05-03-21-07-04-00" LABEL="CentOS 7 x86_64" TYPE="iso9660" PTTYPE="dos"
[root@localhost ~]# ls -l /dev/sd[a-z]
brw-rw----. 1 root disk 8, 0 Feb 25 10:26 /dev/sda

新增swap分割槽操作

  VMware Workstation新增一塊硬碟

  • 在"我的計算機"中選擇該主機--右鍵--設定--新增--硬碟--下一步--下一步--下一步--完成 新增硬碟步驟。

  •  命令:echo "- - -" > /sys/class/scsi_host/host0/scan
  •  1.新增添磁碟,還不能直接顯示出來,要想出現要對磁碟進行掃描(實際生產環境中不需要,都是熱插拔技術):
  • 2.假如 fdisk -l 還是未發現新硬碟,則將上面命令中的host0,替換為host1,host2,....看看;
  • 3.我們再檢視系統日誌/var/log/messages,發現對SCSI裝置進行了一次重新掃描,用fdisk -l也看到了新增加的磁碟了。
檢視新增的硬碟
[root@localhost ~]# echo "- - -" > /sys/class/scsi_host/host0/scan 
[root@localhost ~]# ls -l /dev/sd[a-z]
brw-rw----. 1 root disk 8,  0 Feb 25 10:26 /dev/sda
brw-rw----. 1 root disk 8, 16 Feb 25 10:51 /dev/sdb

[root@localhost ~]# fdisk -l

Disk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x00094eb7

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      616447      307200   83  Linux
/dev/sda2          616448    40462335    19922944   83  Linux

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

方式一:在/dev/sdb磁碟上使用lvm2建立分割槽

(lvm分割槽參考前文:Linux下使用lvm管理)

安裝lvm2
[root@localhost ~]# yum install lvm2 -y
[root@localhost ~]# rpm -qa |grep lvm2
lvm2-libs-2.02.187-6.el7_9.5.x86_64
lvm2-2.02.187-6.el7_9.5.x86_64

方式二:在/dev/sdb磁碟上直接建立物理分割槽

[root@localhost ~]# fdisk /dev/sdb 
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0x3d895f28.

Command (m for help): n  //建立分割槽
Partition type:
   p   primary (0 primary, 0 extended, 4 free)
   e   extended
Select (default p):   //回車,預設p為主分割槽,e為擴充套件分割槽
Using default response p
Partition number (1-4, default 1):   //回車,預設分割槽號
First sector (2048-41943039, default 2048):   //回車(預設)
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-41943039, default 41943039): +8G  //新增分割槽大小
Partition 1 of type Linux and of size 8 GiB is set

Command (m for help): m  //顯示相關命令
Command action
   a   toggle a bootable flag
   b   edit bsd disklabel
   c   toggle the dos compatibility flag
   d   delete a partition
   g   create a new empty GPT partition table
   G   create an IRIX (SGI) partition table
   l   list known partition types
   m   print this menu
   n   add a new partition
   o   create a new empty DOS partition table
   p   print the partition table
   q   quit without saving changes
   s   create a new empty Sun disklabel
   t   change a partition's system id
   u   change display/entry units
   v   verify the partition table
   w   write table to disk and exit
   x   extra functionality (experts only)

Command (m for help): p  //顯示資訊

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x3d895f28

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048    16779263     8388608   83  Linux

Command (m for help): l  //列出所有型別

 0  Empty           24  NEC DOS         81  Minix / old Lin bf  Solaris        
 1  FAT12           27  Hidden NTFS Win 82  Linux swap / So c1  DRDOS/sec (FAT-
 2  XENIX root      39  Plan 9          83  Linux           c4  DRDOS/sec (FAT-
 3  XENIX usr       3c  PartitionMagic  84  OS/2 hidden C:  c6  DRDOS/sec (FAT-
 4  FAT16 <32M      40  Venix 80286     85  Linux extended  c7  Syrinx         
 5  Extended        41  PPC PReP Boot   86  NTFS volume set da  Non-FS data    
 6  FAT16           42  SFS             87  NTFS volume set db  CP/M / CTOS / .
 7  HPFS/NTFS/exFAT 4d  QNX4.x          88  Linux plaintext de  Dell Utility   
 8  AIX             4e  QNX4.x 2nd part 8e  Linux LVM       df  BootIt         
 9  AIX bootable    4f  QNX4.x 3rd part 93  Amoeba          e1  DOS access     
 a  OS/2 Boot Manag 50  OnTrack DM      94  Amoeba BBT      e3  DOS R/O        
 b  W95 FAT32       51  OnTrack DM6 Aux 9f  BSD/OS          e4  SpeedStor      
 c  W95 FAT32 (LBA) 52  CP/M            a0  IBM Thinkpad hi eb  BeOS fs        
 e  W95 FAT16 (LBA) 53  OnTrack DM6 Aux a5  FreeBSD         ee  GPT            
 f  W95 Ext'd (LBA) 54  OnTrackDM6      a6  OpenBSD         ef  EFI (FAT-12/16/
10  OPUS            55  EZ-Drive        a7  NeXTSTEP        f0  Linux/PA-RISC b
11  Hidden FAT12    56  Golden Bow      a8  Darwin UFS      f1  SpeedStor      
12  Compaq diagnost 5c  Priam Edisk     a9  NetBSD          f4  SpeedStor      
14  Hidden FAT16 <3 61  SpeedStor       ab  Darwin boot     f2  DOS secondary  
16  Hidden FAT16    63  GNU HURD or Sys af  HFS / HFS+      fb  VMware VMFS    
17  Hidden HPFS/NTF 64  Novell Netware  b7  BSDI fs         fc  VMware VMKCORE 
18  AST SmartSleep  65  Novell Netware  b8  BSDI swap       fd  Linux raid auto
1b  Hidden W95 FAT3 70  DiskSecure Mult bb  Boot Wizard hid fe  LANstep        
1c  Hidden W95 FAT3 75  PC/IX           be  Solaris boot    ff  BBT            
1e  Hidden W95 FAT1 80  Old Minix      

Command (m for help): t  //修改型別
Selected partition 1
Hex code (type L to list all codes): 82  //修改為Linux swap型別
Changed type of partition 'Linux' to 'Linux swap / Solaris'

Command (m for help): p  //再次顯示,確認修改成功

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x3d895f28

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048    16779263     8388608   82  Linux swap / Solaris

Command (m for help): w  //儲存退出
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

[root@localhost ~]# fdisk -l

Disk /dev/sda: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x00094eb7

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      616447      307200   83  Linux
/dev/sda2          616448    40462335    19922944   83  Linux

Disk /dev/sdb: 21.5 GB, 21474836480 bytes, 41943040 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x3d895f28

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048    16779263     8388608   82  Linux swap / Solaris

格式化swap分割槽
[root@localhost ~]# mkswap /dev/sdb1 
Setting up swapspace version 1, size = 8388604 KiB
no label, UUID=ebe6d07e-a3df-4c08-af8f-8129b0989c72

[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         122        3460          11         351        3543
Swap:             0           0           0
  
開啟swap分割槽
[root@localhost ~]# swapon /dev/sdb1

[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         127        3454          11         351        3537
Swap:          8191           0        8191

[root@localhost ~]# blkid 
/dev/sda1: UUID="0705b568-de2f-40dc-940f-ea2c91b3f059" TYPE="xfs" 
/dev/sda2: UUID="57859f61-6df4-40dc-8da5-6998dc7df3a7" TYPE="xfs" 
/dev/sr0: UUID="2018-05-03-21-07-04-00" LABEL="CentOS 7 x86_64" TYPE="iso9660" PTTYPE="dos" 
/dev/sdb1: UUID="ebe6d07e-a3df-4c08-af8f-8129b0989c72" TYPE="swap

將新新增的交換分割槽新增到/etc/fstab檔案中使之開機啟動
[root@localhost ~]# echo "UUID=ebe6d07e-a3df-4c08-af8f-8129b0989c72  swap  swap  defaults  0  0" >> /etc/fstab

到此就完成了直接用物理分割槽新增為swap

刪除swap分割槽操作

關閉swap
[root@localhost ~]# swapoff /dev/sdb1

註釋掉或刪除/etc/fstab中的分割槽資訊
[root@localhost ~]# sed -i_bak 's/^[^#].*swap*/#&/g' /etc/fstab
[root@localhost ~]# sed -i_bak '/swap/d' /etc/fstab

[root@localhost ~]# fdisk /dev/sdb
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0x8737f2c3.

Command (m for help): m
Command action
   a   toggle a bootable flag
   b   edit bsd disklabel
   c   toggle the dos compatibility flag
   d   delete a partition
   g   create a new empty GPT partition table
   G   create an IRIX (SGI) partition table
   l   list known partition types
   m   print this menu
   n   add a new partition
   o   create a new empty DOS partition table
   p   print the partition table
   q   quit without saving changes
   s   create a new empty Sun disklabel
   t   change a partition's system id
   u   change display/entry units
   v   verify the partition table
   w   write table to disk and exit
   x   extra functionality (experts only)

Command (m for help): d
No partition is defined yet!

Command (m for help): p

Disk /dev/sdb1: 8589 MB, 8589934592 bytes, 16777216 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: dos
Disk identifier: 0x8737f2c3

     Device Boot      Start         End      Blocks   Id  System

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.

WARNING: Re-reading the partition table failed with error 22: Invalid argument.
The kernel still uses the old table. The new table will be used at
the next reboot or after you run partprobe(8) or kpartx(8)
Syncing disks.

[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         101        3695          11         137        3620
Swap:             0           0           0

到此就完全刪除了swap分割槽

新增swap交換檔案操作

使用dd命令建立名為swapfile的swap交換檔案,檔案路徑為/swapfile,bs為單位,count為大小(8G)
[root@localhost ~]# dd if=/dev/zero of=/swapfile bs=1MB count=8192
8192+0 records in
8192+0 records out
8192000000 bytes (8.2 GB) copied, 55.0475 s, 149 MB/s

[root@localhost ~]# df -Th
Filesystem     Type      Size  Used Avail Use% Mounted on
/dev/sda2      xfs        19G  8.6G   11G  46% /
devtmpfs       devtmpfs  2.0G     0  2.0G   0% /dev
tmpfs          tmpfs     2.0G     0  2.0G   0% /dev/shm
tmpfs          tmpfs     2.0G   12M  2.0G   1% /run
tmpfs          tmpfs     2.0G     0  2.0G   0% /sys/fs/cgroup
/dev/sda1      xfs       297M  107M  191M  36% /boot
tmpfs          tmpfs     394M     0  394M   0% /run/user/0

[root@localhost ~]# blkid 
/dev/sda1: UUID="0705b568-de2f-40dc-940f-ea2c91b3f059" TYPE="xfs" 
/dev/sda2: UUID="57859f61-6df4-40dc-8da5-6998dc7df3a7" TYPE="xfs" 
/dev/sr0: UUID="2018-05-03-21-07-04-00" LABEL="CentOS 7 x86_64" TYPE="iso9660" PTTYPE="dos" 

驗證交換檔案大小
[root@localhost ~]# du -sh /swapfile 
7.7G	/swapfile

修改檔案的許可權,避免其他使用者對這個檔案進行誤操作
[root@localhost ~]# ls -l /swapfile
-rw-r--r--. 1 root root 8192000000 Mar 24 14:27 /swapfile
[root@localhost ~]# chmod 600 /swapfile
[root@localhost ~]# ls -l /swapfile
-rw-------. 1 root root 8192000000 Mar 24 14:27 /swapfile

將交換檔案格式化並轉換為swap分割槽
[root@localhost ~]# mkswap /swapfile
Setting up swapspace version 1, size = 7999996 KiB
no label, UUID=42e38c74-4067-499a-bee4-e53542262f91

[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         102         127          11        3704        3515
Swap:             0           0           0

掛載並啟用分割槽
[root@localhost ~]# swapon /swapfile 
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         108         120          11        3704        3508
Swap:          7812           0        7812

設定開機自動掛載該分割槽
[root@localhost ~]# echo "/swapfile swap swap defaults 0 0" >> /etc/fstab

重新生成掛載單元/etc/fstab
[root@localhost ~]# systemctl daemon-reload

刪除swap交換檔案操作

檢視swap
[root@localhost ~]# cat /proc/swaps 
Filename				Type		Size	Used	Priority
/swapfile                               file		7999996	0	-1

[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         110        3687          11         136        3612
Swap:          7812           0        7812

禁用交換檔案  
[root@localhost ~]# swapoff -v /swapfile 
swapoff /swapfile

重新生成掛載單元/etc/fstab
[root@localhost ~]# systemctl daemon-reload

刪除實際檔案
[root@localhost ~]# rm /swapfile -rf

註釋掉或刪除/etc/fstab中的分割槽資訊 
[root@localhost ~]# sed -i_bak 's/^[^#].*swap*/#&/g' /etc/fstab 
[root@localhost ~]# sed -i_bak '/swap/d' /etc/fstab

再次檢查swap
[root@localhost ~]# free -m
              total        used        free      shared  buff/cache   available
Mem:           3934         104        3693          11         136        3618
Swap:             0           0           0

[root@localhost ~]# cat /proc/swaps 
Filename				Type		Size	Used	Priority

附:在lvm2上使用swap【官方文件

相關文章