Bash – Limit TOP to specific processes (without static PIDs)

bashtop

I would like to monitor specific processes via TOP on our application servers via TOP. Currently, I have been using the following in BASH to monitor just the processes that I am interested in:

top -p $(pgrep PSAPPSRV | tr "\\n" "," | sed 's/,$//')

I had thought that this was a great solution, but there are two caveats I was overlooking:

  1. A single process can recycle itself, creating a new PID
  2. When the existing processes are under load, the server can spawn new processes to cope with the load.

Both situations mean that I can't monitor the processes for an extended amount of time if I use a 'snapshot' of the PIDs at point-in-time that I run the command above.

These processes run as a dedicated user. However, this user runs all of the processes associated with the application server. And, an application server may actually consist of 30 processes, but I'm only interested in a specific process.

Is it possible to pass new PIDs into TOP output that is already running?

Or would the best strategy be to re-call TOP at certain intervals, passing in the PIDs at that current time?

Best Answer

top really isn't designed to do what you're trying to do (in fact some versions of top don't even support the -p option).

The best option I can think of for your situation would be to wrap top in a script that calls it repeatedly with the -d and -n options, e.g.

#!/bin/sh
while [ true ]; do
    clear
    top -d1 -n15 -p $(pgrep PSAPPSRV | tr "\\n" "," | sed 's/,$//')
    sleep 1
done

which will make top show one screen with up to 15 processes, sleep for one second, then do it again (until you abort the script with CTRL+C.

This loses top's advanced functionality (like the ability to change sort order - so make sure you specify that if it's important), but will give you the same sort of display without much work.