Per-process swap usage on Linux

It seems that there is no way to retrieve the per-process contribution to the swap page with the standard tools, at least on Lucid. This would only be a minor point in my endless trolling about the fact the Linux is not made for the sysadmins if it was not so hard to get it.

First of all, most searches on the Internet will lead to an answer that is entirely wrong. Most sources claim that VIRT = SWAP + RES (this is verbatim from the top manpage). This means that the size of the allocated virtual space is equal to the resident memory plus the swapped memory. This is obviously wrong, as it doesn’t take into account many reasons why the virtual memory of a process would grow. You might want to check this with this program :

#include <stdio.h>
#include <unistd.h>

int main(int argc, char ** argv)
    char * lapin = malloc(1024*1024*1024);
    return 0;

The memory usage for this program is, on a system with no swap :

$ ps -o pid,size,rss,cmd -p `pgrep memtest`
 6113 1048716 404 /tmp/memtest

A mere 400 kB, for a bit more than 1GB of virtual address space. The reason here is that as long as you do not touch the allocated pages, they will not be committed and will not use physical memory.

The correct answer is to produce a script that will parse /proc/*/smaps. You will find many shell scripts on the Internet, but they spawn tons of processes and are probably not what you want on a swapping host. I suggest either writing a small executable, or just doing it in perl. It should be possible for an experienced monger to produce a one-liner, but this seems to work (sort -g the output) :

#!/usr/bin/perl -w

opendir(my $PROC,"/proc");

print "SWAP\tPID\tEXE\n";

foreach $pid (grep {/^[0-9]+$/} readdir($PROC)) {
    $swap = 0;
    open(my $SMAPS, "/proc/$pid/smaps");
    while(<$SMAPS>) { next if (!/^Swap:\s+(\d+) kB$/); $swap += $1; }
    next if($swap == 0);
    $link = readlink "/proc/$pid/exe";
    print "$swap\t$pid\t$link\n";

One thought on “Per-process swap usage on Linux

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s