Issue
Is there an option for the Linux top command where I can filter processes by name and write the CPU usage of that process every second to a log file?
Solution
top
& pgrep
To filter the output of top
by process name, you can use pgrep
to get a list of PIDs by process name then pass them to the -p
option of top
.
For example:
top -p $(pgrep -d',' http)
Note: the -d','
option delimits the PIDs with commas, which is what is expected by the top -p
.
Note 2: top
will return a failure message if there are no running processes that match the name you specify in pgrep
.
To write the results of top
to a file, use the -n 1
option (only one iteration) and redirect the output to your log file.
top -p $(pgrep -d',' http) -n 1 >> your_log_file
To do that every second, perhaps a while
loop with a sleep
would do?
while :; do top -p $(pgrep -d',' http) -n 1 >> your_log_file; sleep 1; done
To timestamp each entry, you can append the output of date
. E.g.
while :; do top -p $(pgrep -d',' http) -n 1 >> log.txt; date >> log.txt; sleep 1; done
Answered By - Shawn Chin Answer Checked By - Pedro (WPSolving Volunteer)