Linux Restart Process / Application When Memory Threshold Is Reached

bashlinuxshellrestartprocess

Here I needed to kill a c++ process that was leaking memory in order to save the server from meltdown. Very simple while loop that calls the external command "free" and parses it's output with awk to store a variable. Pretty neat and it works.

#!/bin/bash

# Server memory capacity 48GB
PKILL=$(which pkill)
ECHO=$(which echo)
thresHold=47500
BASH=$(which bash)

while true
do 
    highMem=$(free -m | awk '/^\-/' | awk '{print $3}')
    $ECHO $highMem
        if [ $highMem -ge $thresHold ] 
            then 
                $ECHO "We reached the memory limit"
                $PKILL processName
                $BASH /opt/code/bin/application_starter.sh > /dev/null 2>&1
            else
                $ECHO "Memory is under control"
        fi     
sleep 60
done

Jason