当前位置首页 > Linux知识

Linux下swap(交换分区)的增删改

阅读次数:337 次  来源:admin  发布时间:

wap介绍

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添加一块硬盘

在"我的计算机"中选择该主机--右键--设置--添加--硬盘--下一步--下一步--下一步--完成 添加硬盘步骤。

Linux下swap(交换分区)的增删改

命令: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 
FilenameTypeSizeUsedPriority
/swapfile                               file79999960-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 
FilenameTypeSizeUsedPriority

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

Linux下swap(交换分区)的增删改

上一篇:使用debian云映像创建虚拟机
下一篇:ssh远程登录linux服务器