Table of content

Swap Space in Linux

What is Swap Space?

Swap space is utilized when the physical memory is full.

In a situation, when the system needs additional memory resources and RAM is full, the pages in the memory which are not active are shifted to the swap space.

The swap space can assist machines with a small portion of RAM. It is not an alternative to additional RAM. The swap space is present on hard drives that have a slower time to access than physical memory.

The commands to extend swap are dd, mkswap and swapon or swapoff.

The swap size should be twice the size of RAM.

Let us take M as the amount of RAM in GB. S as the amount of swap in GB. Then,

If M<2
then S=M*2
Else 
S=M+2

Adding Swap Size

If we do not have any additional disks, we can create a file somewhere on the filesystem, and utilize that file for the swap space.

  • To create a swap file with the name newswap under / directory with size 1024MB, the command is:
dd if=/dev/zero of=/newswap bs=1M count=1024

Where,

if = read from FILE instead of stdin.

of = write to FILE instead of stdout.

bs = read and write BYTES at a time.

count = total size of the file.

  • To change the permission of the swap file, run the command:
    chmod go-r /newswap​

Or

chmod 0600 /newswap
  • To make the newswap file as a swap file, run the command:
    mkswap /newswap​
  • To enable the newly created newswap file, run the command:
    swapon /newswap​
  • To make the swap file available as a swap area after reboot, run the command:
    vi /etc/fstab​
  • Add the following line to the /etc/fstab file:
    /newswap swap swap defaults 0 0​
  • Save a quit the file.
    :wq!​
  • To verify the newly created swap area is available for use, run the command:
    swapon –s​

or

free –m
  • If we do not want to reboot to verify the system takes all the swap space mentioned in the /etc/fstab, we can do the following, which shall disable and enable all the swap partition within the /etc/fstab:
    swapoff -a
    swapon -a​
About Author :

Myself Debomita Bhattacharjee, an IT employee with 6+ years of experience in Software industry. My area of interest is Automation testing and Front End Development.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions