Share the shell script created to periodically monitor the process with the top command. Specifically, it is as simple as continuing to output the execution result of the top command to the log file in a while loop.
--Local pc
First, share the execution result of the top command to be a shell script as a sample.
$ top -n 1
top - 00:58:08 up 55 min, 1 user, load average: 0.67, 0.58, 0.64
Tasks: 329 total, 1 running, 328 sleeping, 0 stopped, 0 zombie
%Cpu(s): 4.6 us, 0.8 sy, 0.0 ni, 93.1 id, 0.0 wa, 0.0 hi, 1.5 si, 0.0 st
MiB Mem : 15662.8 total, 9716.0 free, 2467.8 used, 3478.9 buff/cache
MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 11582.7 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
9095 gkz 20 0 4616108 107196 70536 S 25.0 0.7 0:00.37 chrome
2487 gkz 20 0 4730532 335940 156620 S 6.2 2.1 2:42.61 gnome-shell
4102 gkz 20 0 321656 12708 11268 S 6.2 0.1 0:05.56 ibus-engine-moz
7243 gkz 20 0 961388 52248 37448 S 6.2 0.3 0:05.53 gnome-terminal-
1 root 20 0 168164 11936 8272 S 0.0 0.1 0:10.67 systemd
The top command can limit the number of screen (frame?) Updates by using the n option. In this article, in order to periodically monitor the CPU usage of any process, we will pipe the result of the top command and use grep to narrow down the output result of a specific process.
toploop.sh
#!/bin/bash
# debug mode
# bash -x toploop.sh $process
# your monitored process, e.g. dockerd
process=$1
starttime=`date +"%Y%m%d_%H%M%S"`
filename=`echo "log/top.log.$process.$starttime"`
while true
do
sleep 5
output=`top -n 1| grep $process`
val=`echo $output | awk '{print $13}'`
if [ "$val" == "$process" ]; then
num=`echo "$output" | grep -oP "[S|R]\s+[0-9]*[.]?[0-9]" | awk '{print $2}'`
date +"%Y%m%d_%H%M%S" >> $filename
echo "$process: $num%" >> $filename
else
date +"%Y%m%d_%H%M%S" >> $filename
echo "$process: notfound" >> $filename
fi
done
&
at the end of the command$ . toploop.sh chrome&
[1] 11175
top.log. $ {Process}. $ {Starttime}
.$ tail -f log/top.log.chrome.20200526_011531
20200526_011602
chrome: notfound
20200526_011608
chrome: 6.2%
kill $ {bash PID}
.Recommended Posts