Raspberry Pi Swap Space

Who took my slice of pi?  

Sometimes I ask myself that while looking in the fridge. This time, I am looking at the top command and see nearly a quarter of the reserved swap space in use.  The question is purely academic, and spurred by curiosity, I wrote a bash script to learn the answer.

The script, swapid, searches through the process list, identifies the process name and amount of swap used, and then sorts the output by swap size. 

With Linux, processes can be viewed and interrogated like a file system. Run

$ ls /proc

and you'll see it sprinkled with subdirectories named with numbers. These numbers correspond to process ids. Inside each of these subdirectories is a file named status, and running

 $ cat status

reveals a bunch of process information.

At this point, it's simply a matter of using awk and grep to pick out the attributes of interest; in this case, "Name" and "VmSwap."

Output is written to the /tmp directory, sorted, printed to the console, and then deleted. 

Source code for swapid

#!/bin/bash
tmpfile="/tmp/swapid.tmp"
if [ -f $tmpfile ]; then rm $tmpfile; fi
for f in /proc/*/status
do
    name=$(grep ^Name $f)
    swap=$(grep ^VmSwap $f)
    echo $name" "$swap | awk '{print $2" "$4" "$5}' | 
        grep -i kb | grep -v grep >> $tmpfile
done
sort -n -k 2.1 $tmpfile
rm $tmpfile

After typing this in using your favorite editor, it helps to make the script executable:

$ chmod +x swapid

Running the script, the last dozen output lines show the largest slices of swap space goes to process php-cgi:

$ ./swapid
. . .
smbd-notifyd 1560 kB
lpqd 1564 kB
php-cgi 1784 kB
php-cgi 1792 kB
php-cgi 1800 kB
php-cgi 1812 kB
php-cgi 2040 kB
php-cgi 2684 kB
php-cgi 2684 kB
php-cgi 2684 kB
php-cgi 2684 kB
php-cgi 2684 kB

So now I have the answer to the question above: the apache2 server took it! And 10 slices to boot!

Comments

Popular posts from this blog

MR2 Check Engine

Bookshelf: UNIX A History and a Memoir

Raspberry Pi 5 Resource Limits