The RAM is a type memory that stores data or programs that are in use by the system. The swap memory (virtual memory) uses a portion of the hard drive as a "slow" RAM. The system uses virtual memory when the RAM use reaches high percentages.
Displaying the memory on a system:
To display the memory usage on a system, we use the below command:
Or we could use the "-h" option for a more readable format as below:
Free memory: is the unused RAM that is not allocated to any program.
Available memory: is a memory already allocated to some programs, that they hold for later use.
When the amount of free RAM decreases, memory will be de-allocated and used by the new processes.
Displaying the Swap:
We use the below command to display the swap space on a system:
swpd: used virtual memory (Swap memory).
si: memory swapped from the disk per second
so: memory swapped to the disk per second
The swap space starts to get used when the RAM use reaches high percentages.
Checking memory usage with the "ps" command:
We can use the "ps" command to see which processes use lot of RAM.
We get the program that consumes most of the memory in the first line:
Then, we could use the below command to investigate further, using the process ID of that process:
It displays the memory usage of different parts of the process.
Using "dmesg" to investigate memory issues:
We could use the below command to look into the kernel messages regarding memory:
The "-i" option is used to look for a word, whether it is written in small or capital letters.
Restarting or stopping the process that consumes memory:
We can stop a process using the below command:
We could use SIGKILL or "-9".
We could also restart the sevice that is consuming too much RAM using the below command:
Adding swap space:
We first create the space that is going to be used as swap "added_swap":
input file : file we use as input.
output file : file we use as output
block size : block size
count : block size count.
The above command fills out a the "file" (added_swap) - that is one gigabytes in size - with null characters.
We could check if the file was created using the "ls -l" command.
We then need to disable the read rights for others and groups the file belong to, so they wouldn't be allowed to write to it:
go : for group and others
-r : removes the read rights using the "-" character.
After giving it the proper rights, we prepare the swap space using:
Then we enable the swap space, so it could be used by the system:
we can check that the swap has been added using the "free -m" command.
We should see an increase in the total swap size.
To be available on reboot, we need to add the swap file to the "/etc/fstab" file:
We are not mounting the swap space, we just mention "swap" as a mount point.
We could also use cgroups to limit the memory usage of processes.