Saturday, June 6, 2015

Creating swap file

One of problems I came across was that I didn't have partition for swap. In modern day, if you have enough RAM, swap partition is not necessary but it is required if you want to use suspend-to-disk. I found out that I could make swap file that will work same as swap partition.

You will need root access:

sudo -s 

Now create actual file

dd if=/dev/zero of=/swapfile bs=1M count=2048

This command will create file named swapfile with size of 2GB (1MB x 2048). You can adjust these numbers to fit your needs.

Let's close huge local vulnerability but giving only root rights to read and write to the file with

chown root:root /swapfile
chmod 0600 /swapfile

After file is created type this command to make it swap

mkswap /swapfile


And to activate swap file

swapon /swapfile


To make your system activate this file after reboot, open /etc/fstab file with

vi /etc/fstab


And insert this line (adjust name of your file accordingly)

/swapfile none swap 0 0 



To check if your file is active or not, type

free -m




Removing Swap file or partition


First find your swap partition with

sudo fdisk -l

And look for Linux Swap file. This is sample output


Device     Boot     Start       End   Sectors  Size Id Type
/dev/sda1  *         2048    206847    204800  100M  7 HPFS/NTFS/exFAT
/dev/sda2          206848 164339711 164132864 78.3G  7 HPFS/NTFS/exFAT
/dev/sda3       164339712 564938406 400598695  191G  7 HPFS/NTFS/exFAT
/dev/sda4       564938750 625139711  60200962 28.7G  5 Extended
/dev/sda5       564938752 621996031  57057280 27.2G 83 Linux
/dev/sda6       621998080 625139711   3141632  1.5G 82 Linux swap / Solaris

In my case, swap partitions is /dev/sda6, to disable swap on this partition I type

swapoff /dev/sda6

Now go to /etc/fstab and comment out line with swap. This is that line in my fstab file:

UUID=9f0f62d3-44fd-4286-9b90-1faff3b4a44c swap                    swap    defaults        0 0

To comment it, just add # on the beginning of the line. After rebooting, using free -m you could check that your swap is not there anymore (or if you had more than 1 swap partition/file it is reduced).

No comments:

Post a Comment