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).
Comments
hmmm
Re: hmmm
vsz
andrss
would be it (or at least something close to the real thing), but apparently I was mistaken.Re: hmmm
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 theSWAP
column intop
's output was in this case not much of a help.hmmm