#!/bin/sh

if [ $# -lt 1 ]; then
    echo "Usage: $0  <process_name> [log_file_path]"
    exit
fi

PROCESS_NAME=$1
PROCESS_PID=$(ps | grep $PROCESS_NAME | grep -v grep | awk '{print $1}')
LOG_FILE=./process_mem_monitor.log

if [ $# -gt 1 ]; then
    LOG_FILE=$2
fi

echo "Monitor memory of process $PROCESS_PID($PROCESS_NAME), and log file is $LOG_FILE."

echo "Monitor memory of process $PROCESS_PID($PROCESS_NAME)." > $LOG_FILE
while true; do
    date >> $LOG_FILE ;
    cat /proc/`pidof $PROCESS_NAME`/status |grep RSS >> $LOG_FILE ;
    top -bn 1 | grep $PROCESS_NAME >> $LOG_FILE ;
    if [ $? != 0 ]; then
        PROCESS_PID=$(ps | grep $PROCESS_NAME | grep -v grep | awk '{print $1}') ;
        if [ $PROCESS_PID ]; then
            echo "$PROCESS_NAME the program has restarted, new process is $PROCESS_PID($PROCESS_NAME)." >> $LOG_FILE
            cat /proc/`pidof $PROCESS_NAME`/status |grep RSS >> $LOG_FILE ;
            top -bn 1 | grep $PROCESS_NAME >> $LOG_FILE ;
        fi
    fi
    sleep 60 ;
done

