温馨提示×

Ubuntu Swapper交换空间

小樊
50
2025-09-22 16:12:22
栏目: 云计算

Ubuntu Swap Space (Swapper) Management Guide

What is Swap Space in Ubuntu?

Swap space is a critical component of Ubuntu’s virtual memory system, serving as reserved disk space that supplements physical RAM (Random Access Memory). When physical memory is exhausted, the system moves inactive memory pages (temporary data not actively used by processes) to swap space, freeing up RAM for active processes. This mechanism prevents system crashes due to memory overload and enables smoother multitasking. Swap space can be configured as a swap file (a dedicated file on an existing partition) or a swap partition (a separate disk partition formatted for swap use).

Key Benefits of Swap Space

  • Prevents Out-of-Memory (OOM) Errors: By offloading idle data to disk, swap space allows the system to handle more applications than physical RAM alone could support.
  • Supports Hibernation: On systems with hibernation enabled, swap space stores the contents of RAM when the system enters sleep mode, ensuring data persists after shutdown.
  • Enhances Multitasking: Even with limited RAM, swap space enables running multiple applications simultaneously by dynamically managing memory allocation.

How to Create Swap Space in Ubuntu

There are two common methods to add swap space: using a swap file (easier for most users) or a swap partition (better for advanced configurations).

Method 1: Create a Swap File (Recommended for Most Users)

  1. Check Existing Swap: Before creating new swap, verify if your system already has swap enabled:

    sudo swapon --show
    

    If no output appears, your system has no active swap.

  2. Create a Swap File: Use fallocate (faster) or dd (more traditional) to create a file of the desired size (e.g., 4GB). Replace 4G with your preferred size:

    sudo fallocate -l 4G /swapfile
    

    If fallocate is unavailable, use:

    sudo dd if=/dev/zero of=/swapfile bs=1M count=4096
    
  3. Set Correct Permissions: Swap files must be readable/writable only by the root user to prevent security risks:

    sudo chmod 600 /swapfile
    
  4. Format the File as Swap: Convert the file into a usable swap space:

    sudo mkswap /swapfile
    
  5. Enable the Swap File: Activate the swap file immediately:

    sudo swapon /swapfile
    
  6. Make Swap Permanent: Add an entry to /etc/fstab to ensure swap is enabled after reboot. Open the file in a text editor (e.g., nano):

    sudo nano /etc/fstab
    

    Append this line at the end:

    /swapfile none swap sw 0 0
    

    Save (Ctrl+O, Enter) and exit (Ctrl+X).

Method 2: Create a Swap Partition (Advanced Users)

  1. Identify Unallocated Space: Use fdisk to list disks and find unallocated space:

    sudo fdisk -l
    
  2. Create a New Partition:

    • Run sudo fdisk /dev/sdX (replace sdX with your disk, e.g., sda).
    • Press n to create a new partition, select p for primary, set the size (e.g., +4G), and assign a partition number.
    • Press t to change the partition type to “Linux swap” (type code 82).
    • Press w to save changes and exit.
  3. Format the Partition: Format the new partition as swap:

    sudo mkswap /dev/sdXn  # Replace sdXn with your partition (e.g., sda2)
    
  4. Enable the Partition: Activate the swap partition:

    sudo swapon /dev/sdXn
    
  5. Make Partition Permanent: Add an entry to /etc/fstab:

    /dev/sdXn none swap sw 0 0
    

How to Monitor Swap Usage

To keep track of swap performance and usage, use these essential commands:

  • View Swap Summary: Check total, used, and free swap space in a human-readable format:

    free -h
    
  • List Active Swap Spaces: Show details (size, type, usage) of currently enabled swap files/partitions:

    sudo swapon --show
    # Or use:
    cat /proc/swaps
    
  • Monitor Real-Time Swap Activity: Use vmstat to track swap operations (e.g., pages swapped in/out per second):

    vmstat 1 5  # Updates every second, shows 5 iterations
    
  • Graphical Interface: For a user-friendly view, open the System Monitor application (search for “System Monitor” in the applications menu) and navigate to the “Resources” tab.

Optimizing Swap Performance

Adjusting Swappiness

The swappiness parameter controls how aggressively the kernel moves data to swap. It ranges from 0 (rarely uses swap) to 100 (uses swap aggressively). The default value is typically 60.

  • Check Current Swappiness:

    cat /proc/sys/vm/swappiness
    
  • Temporarily Change Swappiness (effective until reboot):

    sudo sysctl vm.swappiness=10  # Example: Set to 10 (less aggressive)
    
  • Permanently Change Swappiness: Add the following line to /etc/sysctl.conf:

    vm.swappiness=10
    

    Save the file and run sudo sysctl -p to apply changes.

A lower swappiness value (e.g., 10-30) is ideal for systems with ample RAM (e.g., 8GB+), as it reduces unnecessary disk I/O. For systems with limited RAM (e.g., 4GB or less), a higher value (e.g., 60) may be necessary to prevent OOM errors.

Common Maintenance Tasks

Disabling Swap Temporarily

To disable swap (e.g., for troubleshooting or performance testing), use:

sudo swapoff /swapfile  # Replace with /dev/sdXn for partitions

Deleting Swap Space

  1. Disable Swap:

    sudo swapoff /swapfile
    
  2. Remove from /etc/fstab: Open the file and delete the line corresponding to the swap file/partition.

  3. Delete the File/Partition:

    • For swap files:
      sudo rm /swapfile
      
    • For swap partitions: Use GParted or fdisk to delete the partition.

By following these guidelines, you can effectively manage Ubuntu’s swap space to ensure system stability, optimize performance, and prevent memory-related issues.

0