How to create SWAP SPACE in Linux system
Last updated on March 12th, 2018 at 08:10 pm
Swap file or swap space is a file on Linux file-system that is used to hold programs or pages, in the event that the Physical memory aka RAM of the machine is full. Swap file can help the machines that have little amount of RAM but it can’t be used as a full replacement for RAM.
Swap file is similar to swap partition and any of them can be used in the event system memory runs out. The only difference between the two is that swap partition has a partition dedication to it while the swap file is created as a file & then an amount of hdd space is assigned to it.
In this tutorial, we will learn to create a swap file for Linux machine,
( Also read :- Creating SWAP partition using FDISK & FALLOCATE commands )
Creating Swap file
We need block size to create the swap file, block size is the size of swap file in mb multiplied by 1024. So if we are creating 1gb or 1024 mb swap file, the block size would be 1024 multiplied by 1024, which is equal to 1048576.
Now that we have the block size that we need, we will create the swap file. To create swap file,execute the following command as root user,
$ dd if=/dev/zero of=/swap_file bs=1024 count=1048576
Next change the permission of the swap file, so that its only readable by root,
$ chmod 600 /swap_file
We will now run the ‘mkswap’ command to setup the swap file,
$ mkswap /swap_file
Our swap file is now ready to be used, we just need to turn it on. Execute the following command to turn on the swap,
$ swapon /swap_file
Our system can now use the ‘/swap_file’ as swap space to store the programs or inactive pages. But once we reboot the system , our swap file will no longer work. To make it survive the system reboot, we need to mount the swap file using ‘/etc/fstab’. So open the file & make the following entry it it,
$ vim /etc/fstab
/swap_file swap swap defaults 0 0
Save file & exit. Now our swap file will even work after a system reboot. We can also verify the swap by running command ‘free -m’ & it should show the swap.