The creation of memory swap space (swap) in Linux

swap (memory swap space) in Linux

For the server, because it does not know when a large number of requests will come, it is necessary to reserve a part of swap to buffer the memory usage of the system. There are mainly two practical solutions:

  1. Add a hard disk, partition the hard disk, and format it for memory swap space. (Use the added hard disk as a swap partition)
  2. There is no need to use an additional hard disk, and a part of the mobile hard disk is used in the existing file system for swap space. (create a virtual memory file)

Create a swap partition using a real disk

Steps to create a swap partition:

  • Partition: first use to divide a partition gdisk/fdiskin the disk to the system as swapa partition
  • Formatting: use mkswap 设备文件名format partition to become swap format
  • Use: Use swapon 设备文件名to swap mount the device to start
  • Observation free: swapon -s Observe memory usage through and instructions
  1. List all storage devices view ( lsblk, list block device)

    study@virtual-machine:~$ lsblk
    NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
    loop0    7:0    0 155.6M  1 loop /snap/firefox/1232
    loop1    7:1    0 248.8M  1 loop /snap/gnome-3-38-2004/99
    loop2    7:2    0  81.3M  1 loop /snap/gtk-common-themes/1534
    loop3    7:3    0  43.6M  1 loop /snap/snapd/15177
    loop4    7:4    0     4K  1 loop /snap/bare/5
    loop5    7:5    0  61.9M  1 loop /snap/core20/1405
    sda      8:0    0    60G  0 disk 
    ├─sda1   8:1    0     1M  0 part 
    ├─sda2   8:2    0   513M  0 part /boot/efi
    └─sda3   8:3    0  59.5G  0 part /
    sdb      8:16   0     2G  0 disk  # 未分区
    

    Through the analysis, it can be seen that there are two disks (disks), which sdaare already in the system, sdbbut the disk name of a hard disk is simulated (the name is loop*, you can ignore it, this is a virtual device). In the disk device sda, the disk is divided into three partitions (partition), the name is sda1, sda2, sda3; and for the disk sdb, there is no partition. If you want to see other information, you can view it by adding parameters: lsblk [-dfimpt] [device].

    The loopback device whose name is loop is a pseudo-device (relative to real block devices (block devices include disks, etc.)), and is a technology that uses files to simulate block devices.

  2. View the disk partition method (using partedview, it can list the partition table type and partition information of the disk, but root permission is required)

    study@virtual-machine:~$ sudo parted /dev/sda print
    [sudo] study 的密码: 
    型号:VMware, VMware Virtual S (scsi)
    磁盘 /dev/sda: 64.4GB
    扇区大小 (逻辑/物理):512B/512B
    分区表:gpt
    磁盘标志:
    
    编号  起始点  结束点  大小    文件系统  名称                  标志
     1    1049kB  2097kB  1049kB                                  bios_grub
     2    2097kB  540MB   538MB   fat32     EFI System Partition  启动, esp
     3    540MB   64.4GB  63.9GB  ext4
    

    By partedviewing sdathe partition format of the disk device GPT, then use this as a reference to partition the added device into GPTtype. And since the disk device sdbis only used as a swap space, there is only one useful partition.

    Note here: For MBRformat partitions, use fdiskto process, while GPTpartitions generally use to gdiskprocess. Requires root privileges. Of course, partition operations can also be performed using partedinstructions.

  3. Partition the disk (take GPT as an example, MBR format is similar)

    study@virtual-machine:~$ sudo gdisk /dev/sdb 
    GPT fdisk (gdisk) version 1.0.8
    
    Partition table scan:
      MBR: not present
      BSD: not present
      APM: not present
      GPT: not present
    
    Creating new GPT entries in memory.
    
    Command (? for help): ?  # <== 这里可以输入指令动作,按问号(?)查看可用指令
    b	back up GPT data to a file
    c	change a partition's name
    d	delete a partition          # 删除一个分区
    i	show detailed information on a partition
    l	list known partition types
    n	add a new partition         # 增加一个分区
    o	create a new empty GUID partition table (GPT)
    p	print the partition table   # 印出分区表 (常用)
    q	quit without saving changes # 不储存分区就直接离开 gdisk
    r	recovery and transformation options (experts only)
    s	sort partitions
    t	change a partition's type code
    v	verify disk
    w	write table to disk and exit # 储存分区操作后离开 gdisk
    x	extra functionality (experts only)
    ?	print this menu
    
    Command (? for help): p  # <== 输出目前磁盘的状态
    Disk /dev/sdb: 4194304 sectors, 2.0 GiB  # 磁盘文件名/扇区数与总容量
    Model: VMware Virtual S
    Sector size (logical/physical): 512/512 bytes # 单一扇区大小为 512 Bytes
    Disk identifier (GUID): D8EC9BFC-B0F3-4DD7-899D-2111BDC1E752 # 磁盘的 GPT 识别码
    Partition table holds up to 128 entries
    Main partition table begins at sector 2 and ends at sector 33
    First usable sector is 34, last usable sector is 4194270
    Partitions will be aligned on 2048-sector boundaries
    Total free space is 4194237 sectors (2.0 GiB)
    
    # 分区编号 开始扇区号码 结束扇区号码 容量大小
    Number  Start (sector)    End (sector)  Size       Code  Name
    # 这里内容为空,因为还没有使用,所以没有分区
    
    Command (? for help): n # <== 增加分区的指令
    Partition number (1-128, default 1): 1 # 默认就是 1 号,所以直接按 enter 也行
    First sector (34-4194270, default = 2048) or {
          
          +-}size{
          
          KMGTP}: 
    Last sector (2048-4194270, default = 4194270) or {
          
          +-}size{
          
          KMGTP}: 
    Current type is 8300 (Linux filesystem)
    Hex code or GUID (L to show codes, Enter = 8300):  # 使用默认值即可,这里让你选择未来这个分区预计使用的文件系统!默认都是 Linux 文件系统的 8300
    Changed type of partition to 'Linux filesystem'
    
    Command (? for help): w # <== 保存分区并退出
    
    Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING
    PARTITIONS!!
    
    Do you want to proceed? (Y/N): y
    OK; writing new GUID partition table (GPT) to /dev/sdb.
    The operation has completed successfully.
    

    This is to partition the newly added disk. Since it is a new disk, it is not used, but if a new partition is added on the original disk of the computer, a warning will appear when saving the partition: it means that the disk is Warning: The kernel is still using the old partition table.currently In use, the system cannot load the new partition table right now. partprobe -s The partition table information of the Linux kernel can be updated through commands.

  4. Then use lsblkthe command to check whether the partition is successful: sdbthere is a partition named sdb1partition for the new disk. After the partition is complete, format the partition:

    study@virtual-machine:~$ sudo mkswap /dev/sdb1
    [sudo] study 的密码:
    正在设置交换空间版本 1,大小 = 2 GiB (2146410496  个字节)
    无标签, UUID=585afcd7-ccee-4eb6-be00-3f24495a08e4
    
  5. Use swaponthe command to load the disk partition as swap, and use the freeand swapon -sthis command to observe the memory usage.

    study@virtual-machine:~$ free
             total        used        free      shared  buff/cache   available
    内存:    3983244     1217424     1730200    24784     1035620     2506652
    交换:    2097148           0     2097148
    # 实际内存有3983244K,使用了1217424K,剩余1730200K,使用掉的内存有1035620K用于在缓冲/高速缓存。至于swap空间有2097148K,目前没有被使用。
    
    
    study@virtual-machine:~$ sudo swapon /dev/sdb1 # 载入磁盘分区为交换内存swap
    
    study@virtual-machine:~$ swapon -s  # 列出目前使用的 swap 设备
    Filename		Type		Size		Used	Priority
    /swapfile       file		2097148		0		-2
    /dev/sdb1 		partition	2096104		0		-3
    

    View the current system actual memory size and swap space memory size through freethe command. Use it by swapon 分区设备名loading the formatted swap partition. swapon -sList all swap devices currently in use via . There are two types of discovery, one is in the form of a file (original), and the other is in the form of a partition (partition).

    swapoffOf course, the swap space can be unused by command.

  6. Set automatic settings at boot: The above method is one-time, that is to say, if the system is restarted, the swap partition will disappear. Therefore, a persistent operation is required so that the disk partition can be used as the swap space even when the machine is switched on or off. That is, the partition is written to the file as a swap space /etc/fstab. The required fields are:

    [设备/UUID等] [挂载点] [文件系统] [文件系统参数] [dump] [fsck]
    
    # 追加内容如下:由于不是文件系统,所以没有挂载点,第二个字段写入swap即可
    UUID=585afcd7-ccee-4eb6-be00-3f24495a08e4 swap swap defaults 0 0
    

    The UUIDname comes from the universally unique identifier provided by the format disk operation to represent the device. Its value can be checkedlsblk -f by or .blkid

    An experiment was done, which is /etc/fstabto remove the new disk when there is a swap partition record in the file. The computer is still functioning normally.

Create a swap partition using a file

  1. Create a swap space file/tmp/swap

    study@virtual-machine:~$ dd if=/dev/zero of=/tmp/swap bs=1G count=2 # 创建一个2G大小的文件,需要等一段时间。。
    记录了2+0 的读入
    记录了2+0 的写出
    2147483648字节(2.1 GB,2.0 GiB)已复制,25.5939 s,83.9 MB/s
    
    
    study@virtual-machine:~$ ll -h /tmp/swap  # 查看文件大小
    -rw-r--r-- 1 root root 2.0G  17 21:14 /tmp/swap
    

    ddThe command copies a file in blocks of the specified size and performs the specified transformations while copying. It is a very good data backup tool, but the disadvantage is that it is much slower. The main parameters are:

    • if: input file, input file name, as standard input, specify source file
    • of: output file, output file name, as standard output, specify the destination file
    • bs: Set the block size for reading in/out at the same time, the above setting is a data block size of 1G
    • count: The number of data blocks to be copied only. Therefore, bs*count is the capacity of the file.

    /dev/zeroIt is a special input device file that endlessly provides empty data streams (special data format streams). Its typical usage is to use ddinstructions to overwrite information based on the character streams provided by the file and generate a blank file of a specific size.

  2. mkswapFormat the file /tmp/swapto swapa file format using

    study@virtual-machine:~$ sudo mkswap /tmp/swap 
    mkswap: /tmp/swap: insecure permissions 0644, fix with: chmod 0600 /tmp/swap
    正在设置交换空间版本 1,大小 = 2 GiB (2147479552  个字节)
    无标签, UUID=afacff1f-c390-4dc9-9552-c054968a2d62
    
  3. use swaponwill /tmp/swapstart

    study@virtual-machine:~$ sudo swapon /tmp/swap # 启动作为交换空间
    swapon: /tmp/swap:不安全的权限 0644,建议使用 0600。
    
    study@virtual-machine:~$ swapon -s # 查看swap空间
    Filename				Type		Size		Used	Priority
    /swapfile               file		2097148		0		-2
    /tmp/swap               file		2097148		0		-3
    
  4. Use swapoff to turn off swap file, and set auto-enable

    study@virtual-machine:~$ sudo swapoff /tmp/swap # 关闭交换空间的使用
    
    # 将内容写入到/etc/fstab中,内容如下:
    # 注意这里不要使用UUID,否则系统不会查询文件,而是仅查询区块设备(block device)
    /tmp/swap swap swap defaults 0 0
    

Guess you like

Origin blog.csdn.net/weixin_41012765/article/details/129242141
Recommended