MostlyChris

Thoughts that are my own.

Finding Swap Users

I recently ran across this post when I was trying to find out what was using swap on my server. Credit goes to Erik Ljungstrom here.

Create a file on your Linux box and place the following code in it. We’ll call it getswap.sh.

#!/bin/bash
# Get current swap usage for all running processes
# Erik Ljungstrom 27/05/2011
SUM=0
OVERALL=0
for DIR in `find /proc/ -maxdepth 1 -type d | egrep "^/proc/[0-9]"` ; do
PID=`echo $DIR | cut -d / -f 3`
PROGNAME=`ps -p $PID -o comm --no-headers`
for SWAP in `grep Swap $DIR/smaps 2>/dev/null| awk '{ print $2 }'`
do
let SUM=$SUM+$SWAP
done
echo "PID=$PID - Swap used: $SUM - ($PROGNAME )"
let OVERALL=$OVERALL+$SUM
SUM=0

done
echo "Overall swap used: $OVERALL"

Make it executable.

chmod +x getswap.sh

Find the processes with the most swap usage:

./getswap.sh | sort -n -k 5 

Don’t show processes that are not using any swap.

./getswap.sh | egrep -v "Swap used: 0" |sort -n -k 5

Of course, this all needs to be run as root.

Good luck.

Comments