Swap space is an area in the secondary storage device which is used to supplement system RAM by holding the inactive pages of memory. The combination of system RAM and swap space is referred to as Virtual memory. When the available RAM usage exceeds a specified limit then the kernel will write idle pages belonging to a process into this swap space in order to free up space in the RAM. Whenever any process requires to access the page that was written to the swap area, the kernel will find another idle page to swap with the required page (known as a page fault). Since, the swap area resides on the disk it is very slow to access as compared with RAM so its usage should be kept to minimal. In this post we will learn managing (create/extend) the swap space in Linux.
Let’s start by checking the existing swap space size. Use the free command as shown in the figure below
It shows that 51Mb of total swap is there and all the space is free.
The process of creating a swap space consists of four steps
The steps of creating the partition are same as detailed in How to create disk partitions in Linux? I will repeat the steps here again (but not in detail)
Use the lsblk command to list the exiting disks along with partitions
Now suppose we want to extend the swap space by 512Mb. So, let’s choose /dev/sdb disk for the same. You can choose a disk depending upon how much you want to extend the swap space.
Since, we want to create a swap partition hence the default partition (which is Linux) need to be changed. Follow the steps as shown below.
Press ‘t’ to change the type. 82 is the correct Hex code you want. Just in case you want to see the entire list of codes press ‘L’. You can see that after typing 82 and pressing enter there is a message “Changed type of partition ‘Linux’ to ‘Linux swap/Solaris’ which confirms that the type is changed.
Next, type ‘w’ and finally ‘partprobe’ to update the partition table.
Check the newly created partition /dev/sdb1 of size 512Mb using the lsblk command
The third step is to format the partition. Use the mkswap command for the same.
Use the swapon command to activate the formatted swap space or you can make the swap space persistent for all future reboots by editing the /etc/fstab file and using the swapon -a command.
Open the /etc/fstab file using any editor.
Write this line in the file
/dev/sdb1 swap swap defaults 0 0
Run the swapon -a command
Now check the available swap space again using free command
You can see that the available swap space is now 563Mb (51(original) + 512 (new)).
In case you want to deactivate the swap space use the swapoff command. The swapoff command is successful only if any swapped data can be written to another active swap space and then back into memory, otherwise the command will fail.
Note: If there are multiple swap spaces (as above) the second one becomes available for use only when the first one is completely full. Use the swapon -s command to view the priority list.