In operating systems virtual memory adds an extension to the random access memory of the computing device. This post will explain how to add a virtual memory (swap area) for a Linux based operating system.
Virtual memory (swap) space of a Linux environment could be added using an image file which is created on any partition of the disk.
Initially create an empty file on any location where physical disk space available such as /swap.img
1. vi /swap.img , then save file.
Once the empty file is created, it has to be expanded to the required virtual memory size on the disk.
2. dd if=/dev/zero of=/swap.img bs=1024 count=2M
This will expand the file to 2Gb and the value could be changed by changing X value of ‘X’M.
Once the file is created it has to be defined as a swap file on the swap file system. mkswap command would define above to the swap file system.
3. mkswap /swap.img
Once the new swap file is being registered on the file system, it has to be mounted at each bootup. Hence swap file details has to be included on /etc/fstab.
Before proceed take a backup of the existing fstab as a best practice.
4. cp /etc/fstab /etc/fstab_backup
Add following line to the end of the file and save the file
/swap.img swap swap sw 0 0
In order to activate new swap space either the computer has to be restarted or run the following command to activate the new swap space.
5. swapon /swap.img
Once virtual memory is added it will be displayed as below.