Monday, May 6, 2013

Which processes are using your swap ? (Linux)

Here is a simple bash script which briefly shows you the processes using your Linux's swap area.
#!/bin/bash

exec 2>/dev/null
total=0
printf "pid\t\tprocess\t\tmemory (kB)\n"
while read -r me
do
 ps=$(cat $me/comm)
 res1=$?
 val=($(grep "^VmSwap" $me/status))
 res2=$?
 p=$(basename $me)
 if [[ $res1 -eq 0 && $res2 -eq 0 ]]; then
  if [ ${val[1]} -ne 0 ]; then
   printf "%d\t\t%s\t\t%s\n" "$p" "$ps" "${val[1]}"
   let total=$total+${val[1]}

  fi
 fi
done < <(find /proc/ -mindepth 1 -maxdepth 1 -type d -name "[0-9]*" )
echo "Total(kB):$total"


Sample output (processes not sorted by their memory usage)

2 comments:

Anonymous said...

as of 2.6.30-rc7

Jon Disnard said...

Here is a slightly optimized version:
#!/bin/bash
exec 2>/dev/null
declare -i total
printf '%-2s\t%-9s\t%7s\n' pid process kIB
for proc in /proc/[0-9]*
do
swap=($(awk '/^VmSwap/ {print $2}' $proc/status))
[ "$swap" -ne '0' ] || continue
printf "%-2d\t%-9s\t%7d\n" "${proc##*/}" "$(cat $proc/comm)" "$swap"
total+=$swap
done
echo "Total(KiB):$total"