This freeing up of physical memory will be used for other applications. When the physical memory is available enough, the swap memory area will be brought back to the physical memory.  The administrators ensure that sufficient swap space present in the system so that some free physical memory always available to the operating system. This article provides steps to create or increase swap space and also delete if you need it.

​Do I really need swap space?

Not always, the provided system has a large amount of physical memory (RAM).  But it is recommended to have swap space handy.  The system may crash when the system is run out of physical memory when many applications are running with large memory footprint.  When compared to RAM, disk space is relatively cheap!  

Partition or file?

Swap space can be a dedicated swap partition (recommended), a swap file, or a combination of both. By default, most of the Linux distributions create a dedicated swap partition or a file on the system partition during installation. Windows operating system generally has the swap space as a file.  

Though there is no hard and fast rule to have swap space, it is recommended to have at least 1.5 times the physical memory.  In the case of hibernation, the swap partition should be at least as big as the RAM size.  

Creating swap space

Following are the instructions to create swap space using a file:

Login as root.

sudo su

Create swap file in directory “/var” with name “swapfile”.  At the shell, create the file and set root permissions as follows:

cd /var touch swapfile chmod 600 swapfile ls -la swapfile

Use “dd” command to fill the swap file with 1 GB size (as an example) as follows :

dd if=/dev/zero of=/var/swapfile bs=1024k count=1000

Now setup the swap file:

mkswap /var/swapfile

Enable the swap file:

swapon /var/swapfile

To check whether the new swap file was successfully created, either of the below commands can be used.​

cat /proc/swaps

swapon –show

Add below line to the “/etc/fstab” file so that next time when the system boots, it enables the newly created swap file:

/var/swapfile none swap sw 0 0

Disable and remove a swap file

Disable the swap file.

swapoff /var/swapfile

Delete the swap file.

rm /var/swapfile

Remove the entry from “/etc/fstab” file.

/var/swapfile none swap sw 0 0  

Limitation

The swapping mechanism does have a downside.  Because the swap space resides in hard disks, the access time for swap is slower and hence it cannot be a complete replacement for the physical memory.  

​Conclusion

System administrators can benefit greatly by adding sufficient swap space to keep the system running smoothly.  Regular monitoring of system memory usage helps in determining the size of the swap space. Credit to – Ramakrishna Rujure