78.1 Swap File
20211210
If you are running out of swap memory you can add more by creating a swap file on your storage device (hdd or ssd). Swapping to a file is a little less efficient than swapping to a dedicated swap partition as the kernel needs to access the new swap file through the file system. But since this swap file is only called upon when you’ve run out of RAM and then swap memory on a dedicated partition, the additional performance hit is not much compared to that of swapping itself.
Have a look at what memory you have available using free:
$ free
total used free shared buff/cache available
Mem: 16028508 3987252 3494292 1043004 8546964 10656712
Swap: 1003516 467112 536404
Here we have 16GB memory and 1GB of swap of which something like 467MB is being used.
The swapon command can also show the swap memory utilisation:
$ swapon --show
NAME TYPE SIZE USED PRIO
/dev/dm-2 partition 980M 456.2M -2
Here we have almost 1GB of swap of which 456MB is being used.
To add, for example 4GB, to the swap space create a new file of that size and tell the operating system to use this as swap.
First, check the amount of storage space available:
$ df -h
Filesystem Size Used Avail Use% Mounted on
tmpfs 1.6G 3.2M 1.6G 1% /run
/dev/mapper/vgubuntu-root 467G 417G 26G 95% /
...
We’ll create the new swap file in root (/
) using
fallocate and then ensure it is not generally
available to users to view:
$ sudo fallocate -l 4G /swapfile
$ sudo chmod 600 /swapfile
To set up the new file as a special swapfile we use mkswap:
$ sudo mkswap /swapfile
Setting up swapspace version 1, size = 4 GiB (4294963200 bytes)
no label, UUID=a1a0d080-e4bd-4cd8-ab09-0bb9c4eaf9e0
Now tell the operating system to use the file for swap:
sudo swapon /swapfile
Check it is recognised:
$ sudo swapon --show
NAME TYPE SIZE USED PRIO
/dev/dm-2 partition 980M 456.2M -2
/swapfile file 4G 0B -3
Next, make sure the swap is used after a reboot by adding a line to
/etc/fstab
that results in swapon -a
to add
the new swapfile to swap space:
sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
If you wanted to remove the swap file from usage simply use swapoff:
sudo swapoff /swapfile
Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0
