How to find out which processes are using swap space in Linux?

LinuxOperating SystemOpen Source

Swap space is common in Linux, and it usually is used when the amount of the physical memory(RAM) is full. The idea behind the swap space is that if the operating system needs more memory resources and the RAM doesn’t have any space left, then the pages that are inactive will be moved to the swap space.

It should also be noted that while swap space definitely helps out the RAM on a short basis, they should not be considered a replacement for more RAM.

Now we know a bit about swap spaces, let’s talk about how we can detect which processes are using swap space in Linux.

There are many ways to know about the processes that are making use of swap space, the most basic approach is to use the top command and then press f,, scroll down to where it says SWAP press space followed by typing q.

Though it is recommended to either make use of shell script or use Linux utilities like smem.

Using SMEM

SMEM on linux is a command-line utility that is used to provide diverse reports on memory usage on a lInux system.

Installing SMEM

In order to install smem on your local machine, follow the commands shown below −

For Ubuntu/Fedora

sudo apt-get install smem

For CentOS

yum install smem

Syntax

smem [options]

When we run the command shown below, we will get different processes with their PIDs, Usernames, Commands and their swap memory usage.

Command

smem

Output

PID      User     Command               Swap    USS     PSS    RSS
46740  xxxxxxxx /usr/bin/php-cgi       2904      0       2      4
3623   root     ssh-agent-1             572      4       4      4
53398  xxxxxxx  /usr/bin/php-cgi       2748      4       4      8
53396  immukul  /usr/bin/go-cgi        2788      4       4      8
7855   root     rpc.rquotad             124      4       6    116
7380   root     ssh-agent-1             6e4      4       3    112
34802  root     ssh-agent-1             576      4       8      9

We can clearly notice that the process mentioned in the above output are making use of the swap space.

Another approach to get the processes that are using the swap space is to write a shell script.

Consider the script shown below which will print if any process of the directory that you provide is using a swap space.

Script

SUM=0
OVERALL=0
for DIR in `find /usr/local/ -maxdepth 1 -type d -regex "^/proc/[0-9]+"`
do
   PID=`echo $DIR | cut -d / -f 3`
   PROGNAME=`ps -p $PID -o comm --no-headers`
   for SWAP in `grep VmSwap $DIR/status 2 > /dev/null | awk '{ print $2 }'`
   do
      let SUM=$SUM + $SWAP
   done
   if (( $SUM > 0 )); then
      echo "PID=$PID swapped $SUM KB ($PROGNAME)"
   fi
   let OVERALL=$OVERALL + $SUM
   SUM=0
done
echo "Overall swap used on machine : $OVERALL KB"

Output

Overall swap used on machine : 26067 KB
raja
Published on 29-Jul-2021 12:03:40
Advertisements