Linux设置虚拟内存

https://www.cnblogs.com/yizijianxin/p/10634214.html

创建swap文件

  1. 进入/usr目录
[root@localhost usr]$ pwd
/usr
[root@localhost usr]$ 
  1. 创建swap文件夹,并进入该文件夹
[root@localhost usr]# mkdir swap
[root@localhost usr]# cd swap/
[root@localhost swap]# pwd
/usr/swap
[root@localhost swap]# 
  1. 创建swapfile文件,使用命令dd if=/dev/zero of=/usr/swap/swapfile bs=1M count=4096
[root@localhost swap]# dd if=/dev/zero of=/usr/swap/swapfile bs=1M count=4096
记录了4096+0 的读入
记录了4096+0 的写出
4294967296字节(4.3 GB)已复制,15.7479 秒,273 MB/秒
[root@localhost swap]#

查看swap文件

  1. 使用命令du -sh /usr/swap/swapfile,可以看到我们创建的这个swap文件为4g
[root@localhost swap]# du -sh /usr/swap/swapfile
4.1G	/usr/swap/swapfile
[root@localhost swap]# 

将目标设置为swap分区文件

  1. 使用命令mkswap /usr/swap/swapfile将swapfile文件设置为swap分区文件
[root@localhost swap]# mkswap /usr/swap/swapfile
mkswap: /usr/swap/swapfile: warning: don't erase bootbits sectors
        on whole disk. Use -f to force.
Setting up swapspace version 1, size = 4194300 KiB
no label, UUID=5bd241ff-5375-449d-9975-5fdd429df784
[root@localhost swap]#

激活swap区,并立即启用交换区文件

  1. 使用命令swapon /usr/swap/swapfile
[root@localhost swap]# swapon /usr/swap/swapfile
[root@localhost swap]#
  1. 使用命令free -m 来查看现在的内存,可以看到里面的Swap分区变成了4095M,也就是4G内存。
[root@localhost swap]# free -m
             total       used       free     shared    buffers     cached
Mem:           980        910         70          3          8        575
-/+ buffers/cache:        326        654
Swap:         4095          0       4095
[root@localhost swap]#

设置开机自动启用虚拟内存,在etc/fstab文件中加入如下命令

  1. 使用vim编辑器打开/etc/fstab文件

  2. 在文件中加入如下内容

/usr/swap/swapfile swap swap defaults 0 0

使用reboot命令重启服务器

  1. 输入reboot 命令来重启
	[root@localhost swap]# reboot

	Broadcast message from liaocheng@localhost.localdomain
		(/dev/pts/1) at 3:56 ...

	The system is going down for reboot NOW!
	[root@localhost swap]# Connection to 192.168.136.142 closed by remote host.
	Connection to 192.168.136.142 closed.
	[进程已完成]
  1. 重启完成过后使用free -m 命令来查看现在的内存是否挂在上了。
[root@localhost swap]# free -m
             total       used       free     shared    buffers     cached
Mem:           980        910         70          3          8        575
-/+ buffers/cache:        326        654
Swap:         4095          0       4095
原文地址:https://www.cnblogs.com/yuanyongqiang/p/15650176.html