Thursday, 26 April 2012

Managing Swapfiles in Linux

Swapfiles
If you run anything close to a modern operating system, you almost certainly interact with a swap file. You might be familiar with the basics of how these work: they allow your OS to prioritize more frequently-used pages in main memory and move the less frequently-used ones to disk. But there's a lot going on underneath the covers. Here's a simple guide to swap files in Linux.


Making a new swap file is a simple process. In this example, we'll make a 2 GiB swap file and make it available to the system as additional swap space. We'll use swapfile as the name of the example swap file, but there is nothing special about the name of the file or its extension. You may use anything you wish.

First, we need to create the swap file itself. We'll use a stream of zeroes as the input source (if=/dev/zero), and write it out to a file named swapfile in the root directory. We will write 2048 (count=2048) blocks each 1 MiB in size (bs=1M). Depending on the speed of your hard disks, this may take a little while.


Code Snippet
  1. dd if=/dev/zero of=/swapfile bs=1M count=2048
  2. chmod 600 /swapfile
  3. mkswap /swapfile
  4. swapon -v /swapfile
End of Code Snippet

mkswap - Formats this file and prepares it for use as a swapping space. The mkswap utility sets up a swap area on a device or file.

swapon - After formatting it, the swap can now be added to our system. The swapon utility activates the swap region.



Reboot Persistence
To activate /swapfile after Linux system reboot, add entry to /etc/fstab file. Open this file using a text editor such as vi...
Code Snippet
  1. vi /etc/fstab
End of Code Snippet


Append the following line:
Code Snippet
  1. /swapfile swap swap defaults 0 0
End of Code Snippet

No comments: