Retrieve process memory usage on Linux/Unix

It is quite easy to retrieve total memory usage on a Linux or Unix server, with free command. For example:

free -m
             total       used       free     shared    buffers     cached
Mem:          5963       3516       2446          0        194       1161
-/+ buffers/cache:       2160       3802
Swap:         4095          7       4088

We can see that we are using 3516 Mb over the 5963 Mb availables. If you take only "real used" memory, excluding buffers and caches, then we see that we use only 2160 Mb (second line, second column).

Same if you want to retrieve memory usage for one process, using "ps aux" gives, in the RSS column, the reserved memory for each process :

 ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  10348   700 ?        Ss   Feb24   0:01 init [4]
.../...
root     25639  0.0  0.0  44268   644 ?        Ss   05:30   0:00 /usr/sbin/vsftpd /etc/vsftpd/vsftpd.conf
nobody   25656  0.0  0.0   4576  1316 ?        S    05:30   0:00 /product/ibmhttpserver/V6.1/bin/httpd -d /product/ibmhttpserver/V6.
nobody   25659  0.0  0.0 288004  4284 ?        Sl   05:30   0:00 /product/ibmhttpserver/V6.1/bin/httpd -d /product/ibmhttpserver/V6.
nobody   25661  0.0  0.0 287964  4236 ?        Sl   05:30   0:00 /product/ibmhttpserver/V6.1/bin/httpd -d /product/ibmhttpserver/V6.
cdirect  25730  0.0  0.0   3200  1700 ?        S    05:30   0:00 ftdaemon stf

But what if  you want to sum all memory used by ibmhttpserver processes?

Using a script with shell + awk allows us to have the sum of all processes.

#!/bin/bash

if [ "$1" = "" ] ; then
  echo -n "Nom du process : "
  read process
else
  process=$1
fi

ps aux | grep $process | grep -v grep | awk 'BEGIN { sum=0 } {sum=sum+$6; } END {printf("Taille RAM utilisée: %s Mo\n",sum / 1024)}'

For example :

./memProc ibmhttpserver
Taille RAM utilisée: 15.9492 Mo

Simple, but efficient.

Catégorie: 

Tag: