Thursday, October 18, 2012

Linux: Increase Virtual Memory with External Swap File

Traditionally, Linux has used swap partitions as virtual memory. Swap partitions are usually created automatically by various Linux setup programs, which actually use parted, mkswap etc. as backend. Swap partitions are useful in providing additional memory to Linux when the physical memory is not enough. Also, swap partitions can be used for hibernation so that Linux can resume from the last running state. However, it sometimes happens that Linux runs out of memory and the system becomes almost unresponsive.

When that happens, you need to add more virtual memory. This is normally done by finding available swap partition and using swapon. In the following example, swapon is used on /dev/sdb2 to provide additional vitual memory, which is already formatted as swap partition.

swapon /dev/sdb2

If you can't find another swap partition, you'll have to resize existing partitions to make room for a bigger swap partition or create another one. However, you can't repartition the hard drive while Linux is running from one of the partitions on the hard drive you intend to repartition. In that case, you need to use a swap file. A swap file is a file that can be used as virtual memory just like those huge swap files found on Windows. If the current Linux partition has ample space, skip the following part for mounting Windows partition or attaching USB drive.

If Linux partition is limited in space, you should mount a foreign partition, possibly a NTFS partition containing Windows. A USB drive can be used too, so plug it in if the internal hard drive lacks free space. Then, mount the foreign partition. The command to use depends on the type of foreign partition.

mount -t vfat -o dmask=2,fmask=113 /dev/sdb2 /mnt


mount -t ntfs-3g -o dmask=2,fmask=113 /dev/sdb2 /mnt

Now, use dd to create a zero-filled file.

dd if=/dev/zero of=/mnt/swapfile.bin bs=16M count=64

This creates 1GB swap file. To create a 2GB file, increase count= to 128, and so on. The bs=16M argument specifies that 16 megabytes of zeros are appended to the file each time, which seems to speed up file creation. Then, use mkswap to format the file.

mkswap /mnt/swapfile.bin

The swapfile can be used now. Use swapon to add virtual memory with the swap file.

swapon /mnt/swapfile.bin

To check the status of the swap usage, any of the following commands can be used.

  • cat /proc/swaps
  • free -k
  • swapon -s

After you have no more use of the swap file, make sure to run swapoff and umount if necessary.

swapoff /mnt/swapfile.bin
umount /mnt

About This Blog

KBlog logo This blog seeks to provide useful information to people, based on the author's knowledge and experience. Thanks for visiting the blog and posting your comments.

© Contents by KBlog

© Blogger template by Emporium Digital 2008

Follow by Email

Total Pageviews