- [Instructor] Hello again and welcome to the next video
of section eight, listing the top 10
CPU consuming processes in an hour.
In the last video, we learned about
how to collect information about
logged-in users, boot logs and boot failures.
In this video, we'll discuss process monitoring and logging.
CPU is a major resource, and it is good to keep track of
the processes that consume most of the CPU
in a period of time.
By monitoring the CPU usage for a certain period,
we can identify the processes that keep the CPU busy
all the time, and troubleshoot them
to efficiently use the CPU.
PS command is used for collecting details
about the processes running on the system.
They can be used to gather details
such as CPU usage, commands under execution,
memory usage, status of processes, and so on.
Processes that consume the CPU for one hour can be logged,
and the top 10 can be determined
by proper usage of ps and text processing.
Let's go through the following shell script
for monitoring and calculating CPU usages in one hour.
A sample output is as follows.
In the proceeding script, the major input source like this
stands for the command name
and pcpu stands for the CPU usage in percent.
It will output all the process names
in the CPU usage in percent.
For each process, there exists a line in the output.
Since we need to monitor the CPU usage for one hour,
we repeatedly take usage statistics using this,
and append this to a file running inside a for loop
with 60 seconds wait in each iteration.
This wait is provided by sleep 60.
It will execute ps once in each minute.
It's used to strip off the header
and command percent CPU in the ps output.
This signifies that it is the process ID
of the current script.
Suppose PID is 1345.
During execution, it will be replaced like this.
We placed this file in /tmp since this is a temporary file.
The statistics file will be ready after one hour,
and will contain 60 sets of entries,
each set containing entries corresponding to the
process status for each minute.
Then, awk is used to sum the total CPU usage
for each process.
An associative array process is used for the
summation of CPU usages.
It uses the process name as the array index.
Finally, it sorts the result with a numeric reverse sort
according to a total CPU usage
and pass through head to obtain
the top 10 usage entries.
Awesome, we've successfully learned about
listing the top 10 CPU consuming processes in an hour.
In the next video, we'll lean how to monitor
command outputs with Watch.