Admins eHow SysAdmin Tips & Tricks

January 11, 2022

Log the memory usage of a process in Linux

Filed under: linux — Tags: , , , — admin @ 10:27 pm

Create log_memory_usage.py with following contents :

#! /usr/bin/python3

import json, psutil, datetime, sys, time

f = open('memory_usage_'+sys.argv[1]+'.log', 'a')

while True:
  txt=json.dumps((datetime.datetime.now().isoformat(),psutil.Process(int(sys.argv[1])).memory_info()._asdict()))+"\n"
  f.write(txt)
  f.flush()
  time.sleep(60)

Make it executable :

chmod +x log_memory_usage.py

Usage :

./log_memory_usage.py PID

By default it logs the memory usage info every 60 seconds in a file named memory_usage_PID.log in the same folder, if you want, you can change time.sleep(60) in the code to suit your needs.

August 22, 2014

Kill a process with high CPU usage in Linux

Filed under: linux — Tags: , , , , , — admin @ 5:19 pm

Sometimes you may need to kill hanged processes with high CPU usage automatically. the following script can help you to do it :

#!/bin/bash
PROCESSNAME=''
HL=10

IFS=$'\n'
L=$(ps aux | grep $PROCESSNAME)
for fn in $L; do
        PID=$(echo $fn | awk '{print $2'})
        LOAD=$(echo $fn | awk '{print $3'})
        if [ $(echo "$LOAD > $HL" | bc -l ) -eq 1 ]
        then
                kill -9 $PID
                echo "Killed $PID"
        fi
done

Set PROCESSNAME to the process name which you want to be checked and HL to high load threshold.
Please note the load is based what ‘ps’ command reports and not what you see inside ‘top’.

Powered by WordPress