Tuesday, May 19, 2009

How to Create a swap file in Linux partition

Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.

Swapping is necessary for two important reasons. First, when the system requires more memory than is physically available, the kernel swaps out less used pages and gives memory to the current application (process) that needs the memory immediately. Second, a significant number of the pages used by an application during its startup phase may only be used for initialization and then never used again. The system can swap out those pages and free the memory for other applications or even for the disk cache.

Steps to create swap file

1. Use the "dd" command to create a file.

dd if=/dev/zero of=/aSwapFile bs=1024 count=65536

where dd: - is used to copy a specified number of bytes from an Input file (if) to an Output file (of).
Here the dd command copy null characters from the special file "/dev/zero" and copy it to the output file "aSwapFile" in the "/" directory. The "bs" specifies that the characters are read as BYTES. The "count" specifies the size of the bytes block that is to be created in the output file.

2. Use the "mkswap" command to set up the Linux swap area on the file created.

mkswap /aSwapFile

3. Use the "swapon" command to activate the swap file created.

swapon /aSwapFile

4. Edit the fstab "/etc/fstab" to enable the swap after a reboot.

vi /etc/fstab
(Add the following line to the fstab file.)
/aSwapFile swap swap defaults 0 0