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


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<br>

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM