[Note] A shell script that checks the CPU usage of a specific process in a while loop.

0. Introduction

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.

1. Verification environment, etc.

--Local pc

2. Execution result of top command

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.

3. Source code

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

4. Execution method

4-1. Execute the command in the background with & at the end of the command

$  . toploop.sh chrome&
[1] 11175

4-2. After executing the shell script, follow the log file update with the tail command.

$ tail -f log/top.log.chrome.20200526_011531
20200526_011602
chrome: notfound
20200526_011608
chrome:  6.2%

5. Reference

P.S. I also do Twitter, so if you follow me, I'll be happy to cry :)

@gkzvoice

Recommended Posts

[Note] A shell script that checks the CPU usage of a specific process in a while loop.
Process the contents of the file in order with a shell script
Process the files in the folder in order with a shell script
Make a note of the list of basic Pandas usage
A shell program that becomes aho in multiples of 3
A script that can perform stress tests according to the number of CPU cores
A note for embedding the scripting language in a bash script
Note 2 for embedding the scripting language in a bash script
Get the number of specific elements in a python list
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
[Note] Import of a file in the parent directory in Python
A set of script files that do wordcloud in Python3
A Python script that compares the contents of two directories
I wrote a script that splits the image in two
It is said that Fabric cannot get the status code in the middle of the pipe in the shell script.
Write a script in Shell and Python to notify you in Slack when the process is finished
The story of creating a bot that displays active members in a specific channel of slack with python
pandas Fetch the name of a column that contains a specific character
Shell script (Linux, macOS) that outputs the date of the last week
Conditional branch due to the existence of a shell script file
A function that measures the processing time of a method in python
[python] A note that started to understand the behavior of matplotlib.pyplot
A note about the functions of the Linux standard library that handles time
A useful note when using Python for the first time in a while
[Python] Note: A self-made function that finds the area of the normal distribution
[Note] Based on the latitude and longitude of the CSV file, we created a script that extracts data in the target range and adds a mesh code.
The story of creating Botonyan that returns the contents of Google Docs in response to a specific keyword on Slack
Implement part of the process in C ++
How to pass the execution result of a shell command in a list in Python
A collection of Numpy, Pandas Tips that are often used in the field
Note) Batch conversion of specific symbols contained in a character string with a dictionary
Create a BOT that displays the number of infected people in the new corona
Output the number of CPU cores in Python
Get the caller of a function in Python
Make a copy of the list in Python
Find the number of days in a month
Rewriting elements in a loop of lists (Python)
[Note] About the role of underscore "_" in Python
Visualized the usage status of the sink in the company
Output in the form of a python array
Launch a shell while a Python script is running
A shell program that displays the Fibonacci sequence
When a file is placed in the shared folder of Raspberry Pi, the process is executed.
Note that I was addicted to npm script not passing in the verification environment
Get the value of a specific key in a list from the dictionary type in the list with Python
Let's understand the standard input / output of bash together and write a shell script.
A note on the library implementation that explores hyperparameters using Bayesian optimization in Python
[Python] A program that finds the shortest number of steps in a game that crosses clouds
[Python] Change the text color and background color of a specific keyword in print output
A memo that implements the job of loading a GCS file into BigQuery in Python
[Python] Leave only the elements that start with a specific character string in the array
Note that the method of publishing modules to PyPI has changed in various ways.
A script that transfers tweets containing specific Twitter keywords to Slack in real time
A note that runs an external program in Python and parses the resulting line
A simple cache of values in the property decorator. Read only. Note that it keeps caching until the object is deleted.