• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 631
  • Last Modified:

top: filter by command, user, CPU usage and time running

I want top to show ONLY processes that match the following:
Command: PHP
User: foobar
CPU Usage: Greater than 10%
Time: Has run for at least 30 seconds

0
hankknight
Asked:
hankknight
1 Solution
 
Gerwin Jansen, EE MVETopic Advisor Commented:
Don't think you can do this with top as it cannot filter on the PHP command. It can filter a user but not cpu > 10% and time > 30s.

I would recommend a script that starts with a top command like this:
top -b -n1 -u foobar | grep foobar | grep PHP

Open in new window


This will give you output with on the first line (if they exists) a list of PHP process of user foobar with the current CPU load in column #9

Then filter the output for CPU load > 10% with awk, like this:
top -b -n1 -u foobar | grep foobar | grep PHP | awk '$9 > 10.0'

Open in new window


Last filter again on column 11 that has cumulative CPU time, like this:
top -b -n1 -u foobar | grep foobar | grep PHP | awk '$9 > 10.0' | awk '$11 > "0:30.00"'

Open in new window


Put in a small script that adds a loop and a sleep, like this for example:
while [ 1 = 1 ]
do
top -b -n1 -u foobar > tl.txt
head -7 tl.txt > hdr.txt
cat tl.txt | grep foobar | grep PHP | awk '$9 > 10.0' | awk '$11 > "0:30.00"' > pl.txt
clear
cat hdr.txt pl.txt
sleep 3
done

Open in new window


The script above will start displaying your 'top' with 3s intervals. Note that you will only see a header when the filter criteria are not met. You may have to change column numbers depending your top output.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now