How can I display the memory usage of each process if I do a 'ps -ef'?

In Linux, how can I display memory usage of each process if I do a ps -ef? I would like to see the 'virtual memory', 'res memory', 'shared memory' of each progress. I can get that via top, but I want the same info in ps -ef so that I can pipe the output to grep with my process name.


Solution 1:

Obtaining memory usage through ps is pretty unreliable. If you have a newer kernel it should support /proc/pid#/smaps which gives you some detailed information on each processes memory usage. Below is a pretty dirty and quick script to loop through each process that is open and grab the Size, Rss, Pss and Shared Clean/Dirty usage. Hopefully it can be useful in some kind of way.

#!/bin/bash

for pid in $(ps -ef | awk '{print $2}'); do
    if [ -f /proc/$pid/smaps ]; then
            echo "* Mem usage for PID $pid"
            echo "-- Size:"
            cat /proc/$pid/smaps | grep -m 1 -e ^Size: | awk '{print $2}'
            echo "-- Rss:"
            cat /proc/$pid/smaps | grep -m 1 -e ^Rss: | awk '{print $2}'
            echo "-- Pss:"
            cat /proc/$pid/smaps | grep -m 1 -e ^Pss: | awk '{print $2}'
            echo "Shared Clean"
            cat /proc/$pid/smaps | grep -m 1 -e '^Shared_Clean:' | awk '{print $2}'
            echo "Shared Dirty"
            cat /proc/$pid/smaps | grep -m 1 -e '^Shared Dirty:' | awk '{print $2}'
    fi
done

Solution 2:

@user26528's answer doesn't quite calculate the memory correctly - you need the sum of the mappings in smaps, not just the top one. This script should do it:

#!/bin/bash

for pid in $(ps -ef | awk '{print $2}'); do
    if [ -f /proc/$pid/smaps ]; then
        echo "* Mem usage for PID $pid"     
        rss=$(awk 'BEGIN {i=0} /^Rss/ {i = i + $2} END {print i}' /proc/$pid/smaps)
        pss=$(awk 'BEGIN {i=0} /^Pss/ {i = i + $2 + 0.5} END {print i}' /proc/$pid/smaps)
        sc=$(awk 'BEGIN {i=0} /^Shared_Clean/ {i = i + $2} END {print i}' /proc/$pid/smaps)            
        sd=$(awk 'BEGIN {i=0} /^Shared_Dirty/ {i = i + $2} END {print i}' /proc/$pid/smaps)
        pc=$(awk 'BEGIN {i=0} /^Private_Clean/ {i = i + $2} END {print i}' /proc/$pid/smaps)
        pd=$(awk 'BEGIN {i=0} /^Private_Dirty/ {i = i + $2} END {print i}' /proc/$pid/smaps)
        echo "-- Rss: $rss kB" 
        echo "-- Pss: $pss kB"
        echo "Shared Clean $sc kB"
        echo "Shared Dirty $sd kB"
        echo "Private $(($pd + $pc)) kB"
    fi
done