# CentOS7 设置虚拟内存

## 查看当前虚拟内存

以 MiB 为单位查看当前系统内存使用情况：

```
free -m
```

> ```
>               total        used        free      shared  buff/cache   available
> Mem:            990         114          63          12         812         720
> Swap:             0           0           0
> ```

Swap 交换分区大小即为当前虚拟内存大小。

## 增加虚拟内存

创建一个 1GiB 大小空文件 `/var/swap` ：

```
sudo dd if=/dev/zero of=/var/swap bs=1M count=1024
```

> **Tips:**
>
> * `if=/dev/zero` 表示读入空字符串
> * `of` 指定输出文件
> * `bs` 指定单次读写的块大小（bytes）
> * `count` 指定拷贝的快数量
> * `bs` 和 `count` 的乘积大小即为输出的文件大小，一般虚拟内存大小设置为物理内存的1-2倍
> * OpenVZ 架构的 VPS 不支持手动添加交换分区

设置该文件权限为只有拥有者（root）可以读写：

```
sudo chmod 600 /var/swap
```

将该文件设置为交换分区（虚拟内存文件）：

```
sudo mkswap /var/swap
```

启用交换分区：

```
sudo swapon /var/swap
```

切换至 root 用户，写入交换分区信息到开机分区挂载配置文件中：

```
echo '/var/swap swap swap default 0 0' >> /etc/fstab
```

## 删除虚拟内存

停止交换分区：

```
sudo swapoff /var/swap
```

删除交换分区文件：

```
sudo rm -rf /var/swap
```

切换至 root 用户，修改开机分区挂载配置文件：

```
vim /etc/fstab
```

删除交换分区信息：

```
/var/swap swap swap default 0 0
```

保存退出。


---

# 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://avincheng.gitbook.io/notebook/linux/centos/centos7-she-zhi-xu-ni-nei-cun.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.
