How to find the processes using the most swap space in Linux

There's already a good answer to the question at stackoverflow. They suggested to use the top command, then change the sorting field to "swap" by hitting O and p. Unfortunately (afaik) there's no way to do this in batch mode (using the -b switch) and save the top swap using prorcesses in a file. There's another method: use the ps command.
psres=$(ps -eo rss,vsz,user,pid,tty,time,cmd); set -- $(/bin/echo "$psres" | head -n1); shift; shift; echo "SWAP $*"; echo "$psres" | awk 'BEGIN {ORS=""; getline} {print $2 - $1 " "; for (i=3; i<NF; i++) print $i " "; print $NF "\n"}' | sort -rn | head

The "swap" field of top is described by the manpage as: "The swapped out portion of a task’s total virtual memory image."

The "vsz" field of ps is described by the manpage as: "virtual memory size of the process in KiB (1024-byte units). Device mappings are currently excluded; this is subject to change."
The "rss" field of ps is described by the manpage as: "resident set size, the non-swapped physical memory that a task has used (in kiloBytes)."

The difference of "vsz" and "rss" should provide the swap usage. The result from this formula is almost equal to the values in the "swap" field of the top command (the discrepancy is minimal).

P.S.: I've turned this ps processing command into a shell script (see the attachment of this post) that you can use (eg. through crontab) to periodically log the top swap using processes (with the -s switch of the script) or the top physical memory using processes (this is the default).

AttachmentSize
process_memory_monitor.sh1.94 KB

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

hmmm

I do not think that "swap used" = sum(vsz) - sum (rss). Try running your script on a machine with swap disabled.

Re: hmmm

Unfortunately you're right. Thanks for pointing out the mistake in my assumption. Do you know the "proper" way to get the swap usage of a process? Shock I really hoped that the difference of vsz and rss would be it (or at least something close to the real thing), but apparently I was mistaken. Sad

Re: hmmm

On the other hand, in my experience in a system with configured swap space and high swap usage the process with the highest vsz - rss value used to be the culprit ... even if it's not the actual and precise amount of swap space used by that process. Actually I created this script only for this reason: to find the process that was responsible for high swap usage on one of our servers. And the SWAP column in top's output was in this case not much of a help.

hmmm

the script is very useful thank you so much

Syndicate content