# swap分区

linux中的交换分区类似于windows中的虚拟内存。当物理内存已经被用完时，如果我们再起一个新的进程，那么就会出现内存不足。此时，系统可以把没有活动的某个进程在内存中的内容置换到磁盘的某个空间下，这样新的进程就有内存可用。这个磁盘空间可以是一个交换分区，也可以是一个文件（因为文件也会战占用磁盘空间的大小），一般我们使用的是交换分区。

接下来，我们来看一下如何创建一个交换分区并且使用它。我们的初始条件如下，磁盘`/dev/sdb`下已经有了一个大小为50G的主分区`/dev/sdb1`

```
[root@localhost ~]# lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    1   837G  0 disk 
├─sda1   8:1    1    50G  0 part /
└─sda2   8:2    1   787G  0 part 
sdb      8:16   1 223.4G  0 disk 
├─sdb1   8:17   1    50G  0 part 
└─sdb2   8:18   1 173.4G  0 part
```

接着，我们把该分区的类型转换为`Linux Swap`类型。执行命令`fdisk /dev/sdb`，然后输入命令`t`，然后输入`1`选择分区`/dev/sdb1`，然后输入`82`（表示`Linux Swap`类型），然后输入`w`保存与退出。

```
[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.


Command (m for help): t
Partition number (1,2, default 2): 1
Hex code (type L to list all codes): 82
Changed type of partition 'Linux' to 'Linux swap / Solaris'

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

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

然后执行`partprobe`，再查看分区情况，发现`/dev/sdb1`已经变成了`Linux Swap`类型

```
[root@localhost ~]# partprobe
[root@localhost ~]# fdisk -l /dev/sdb

Disk /dev/sdb: 239.9 GB, 239902654464 bytes, 468559872 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: 0x93de47a2

   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1            2048   104859647    52428800   82  Linux swap / Solaris
/dev/sdb2       104859648   468559871   181850112   83  Linux
```

接下来我们使用`mkswap`命令将`/dev/sdb1`格式化为swap文件系统，然后使用命令`blkid`查看分区的文件系统类型。可以看出，`/dev/sdb1`已经是`swap`类型的文件系统了。下面的输出中有两点需要注意：（1）`mkswap`命令的输出中有`wiping old xfs signature`，这是因为`/dev/sdb1`之前已经被格式化为`xfs`类型的系统了；（2）`blkid`命令的输出中没有看到`/dev/sda2`与`/dev/sdb2`，这是因为这两个分区还没有被格式化为某种类型的文件系统。

```
[root@localhost ~]# mkswap /dev/sdb1
mkswap: /dev/sdb1: warning: wiping old xfs signature.
Setting up swapspace version 1, size = 52428796 KiB
no label, UUID=5a24c22c-f06f-47b3-a85e-de9168d03d4e
[root@localhost ~]# blkid
/dev/sda1: UUID="da3cfe99-417c-4e06-b652-22171c0c340a" TYPE="xfs" 
/dev/sdb1: UUID="5a24c22c-f06f-47b3-a85e-de9168d03d4e" TYPE="swap"
```

接下来，我们便可以使用命令`swapon`激活swap分区`/dev/sdb1`，然后使用命令`swapon -s`或`cat /proc/swaps`查看已经激活的swap分区及大小（`swapon -s`实际上就是读取文件`/proc/swaps`中的内容）。发现`/dev/sdb1`已经开启了。至于大小为什么变成了49G少了1G，这个暂时还不清楚。

```
[root@localhost ~]# swapon /dev/sdb1
[root@localhost ~]# swapon -s
Filename                                Type            Size    Used    Priority
/dev/sdb1                               partition       52428796        0       -1
[root@localhost ~]# free -h
              total        used        free      shared  buff/cache   available
Mem:           125G        1.5G        118G         20M        5.2G        123G
Swap:           49G          0B         49G
```

当然，使用`swapon /dev/sdb1`命令可以激活swap分区，但是主机重启后该分区又会处于非激活状态。要想实现主机重启后自动激活swap分区`/dev/sdb1`，需要在`/etc/fstab`文件中添加如下一行

```
/dev/sdb1       swap    swap    defaults        0       0
```

## 关闭swap分区

如果要关闭swap分区`/dev/sdb1`，执行命令`swapoff /dev/sdb1`即可。如果要关闭所有的swap分区，执行命令`swapoff -a`。关闭后，我们使用命令`cat /proc/swaps`查看开启的swap分区，发现已经没有了。

```
[root@localhost ~]# swapoff -a
[root@localhost ~]# cat /proc/swaps 
Filename                                Type            Size    Used    Priority
[root@localhost ~]# free -h
              total        used        free      shared  buff/cache   available
Mem:           125G        1.5G        118G         20M        5.2G        123G
Swap:            0B          0B          0B
```

如果我们在`/etc/fstab`设置了swap分区的相关行，那么我们执行`swapoff -a`只会暂时关闭swap分区，主机重启后又会开启。所以要彻底关掉swap分区，需要注释或删除`/etc/fstab`文件中包含`swap`的所有行。

## 回收swap分区

如果我们不想要swap分区，想把它回收作为一个普通的主分区使用。那么，我们可以按照以下的步骤来回收。首先，关闭激活的swap分区，删除`/etc/fstab`中含有`swap`的行；然后，使用`fdisk`命令将该分区转换为`Linux`（83）类型的分区或者直接使用`fdisk`命令删除这个分区。

## Reference

\[1] <https://blog.csdn.net/ITlinuxP/article/details/78785079>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://pshizhsysu.gitbook.io/linux/ci-pan-yu-fen-qu/swapfen-qu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
