Saturday, October 27, 2012

linux: logging top processes by cpu or memory

I wanted to log the processes consuming cpu and memory

First thought was to use top in the batch mode (-b).
-c to show the process name.
-n 1 to capture for 1, to run for 1 frame
   
$ top -b -c -n 1 > top_$(date +"%Y-%m-%d_%H%M").log

But I was not getting the complete process/command name.

Later I  used the below technique and it was quite helpful

#!/bin/bash

log_file=top_$(date +"%Y-%m-%d_%H%M").log
echo 'user    %cpu    %mem    pid    elapsed time    command' > $log_file
echo ' =========== CPU ===========' > $log_file
ps -eo user,pcpu,pmem,pid,etime,command | sort -rn -k2 | head -11 > $log_file
echo ' ========== MEMORY ==========' >> $log_file
ps -eo user,pcpu,pmem,pid,etime,command | sort -rn -k3 | head -11 >> $log_file

Observation:

1. 'ps aux' is a wonderful command

2. ps command itself has --sort <fieldname>, but there is no reverse sorting

No comments: