Friday, January 18, 2008

Linux Process Memory Usage

The following shell script is used to monitor the memory usage of a process.
Save the following script in a file (for ex, memusage.sh) and run it with the process name you want to monitor.

for ex, ./memusage.sh myapp
Now the script log the mem usage in memusage.csv file for every 2 secs. You can change the time period by change the PERIOD value in the script.

#!/bin/sh
#GetmemUsageModified2
USAGE="Usage: $0 processName"
if [ $# -ne 1 ]; then
echo $USAGE
exit 1
fi
# In case the monitored process has not yet started
# keep searching until its PID is found
PROCESS_PID=""
while :
do
PROCESS_PID=`/sbin/pidof $1`
if [ "$PROCESS_PID.X" != ".X" ]; then
break
fi
done
LOG_FILE="memusage.csv"
echo "ElapsedTime,VmSize,VmRSS" > $LOG_FILE
ELAPSED_TIME=`date`
PERIOD=2 # seconds
while :
do
if [ -d /proc/$PROCESS_PID ] ; then
VM_SIZE=`awk '/VmSize/ {print $2}' < /proc/$PROCESS_PID/status`
if [ "$VM_SIZE.X" = ".X" ]; then
continue
fi
VM_RSS=`awk '/VmRSS/ {print $2}' < /proc/$PROCESS_PID/status`
if [ "$VM_RSS.X" = ".X" ]; then
continue
fi
echo "$ELAPSED_TIME,$VM_SIZE,$VM_RSS" >> $LOG_FILE
sleep $PERIOD
VM_SIZE=""
VM_RSS=""
ELAPSED_TIME=`date +%H:%M:%S:%N`
else
echo "$1 is no longer a running process"
exit 0
fi
done

No comments: