3

Is there an option for linux top command where i can filter processes by name?

For example, I only want to monitor python processes (there are several of them), and I'd like to do something like top -option "python" or something like that.

4 Answers 4

6

When you want information on processes, the answer is always ps

It is simple, and yet it has a ridiculous number of options.

Try this one:

ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10

Should give you the top 10, by cpu usage.

3
  • In the OP's case you want to grep for python before sorting
    – voretaq7
    Feb 8, 2010 at 23:03
  • wow, ps rocks! This command did it: watch "ps -eo pcpu,pid,user,args | grep python". Funny thing is that watch ends up in the output as well, because its command contains "python" :-)
    – mgs
    Feb 8, 2010 at 23:15
  • try: watch "ps -eo pcpu,pid,user,args | grep [p]ython"
    – monomyth
    Feb 8, 2010 at 23:22
2

This approximates the output of top:

watch 'ps axo pid,user,pri,nice,vsz,rsz,size,s,pcpu,pmem,time,cmd|grep "[p]ython\|PID USER"'
0

You could always do "top | grep python" but I'm assuming you want something more dynamic

4
  • Won't work: top's output is dynamic and is not grepable.
    – wzzrd
    Feb 8, 2010 at 22:52
  • 2
    Actually this will work on almost all systems (top is usually smart about not doing dynamic updates if it's being piped - you'll get one screen and an exit). You can also run top -d[count] (at least on FreeBSD) to get [count] displays.
    – voretaq7
    Feb 8, 2010 at 22:59
  • top | grep "python" doesn't do anything
    – mgs
    Feb 8, 2010 at 23:07
  • Works fine for me. Feb 8, 2010 at 23:47
0

My Perl skills are basics, but to get a real Top filtered by name, save this code to a file called topn.pl:

#!/usr/bin/perl

shift @ARGV;
$name = shift @ARGV;
@pids = `/bin/ps -eo pid,user,args | /bin/grep   $name   | /bin/grep -v grep |   /usr/bin/tr -s " "  `;

$arg = "";
foreach (@pids) {
        $_ =~ /^\s([0-9]+)\s/;
        $pid = $1;
        $arg .= " p $pid " if $pid != "";
}

exec("/usr/bin/top $arg @ARGV");

Usage: topn.pl -n FOO c 2 where FOO is the process name to be be grep. The rest of the args are passed to top.

Top accepts at max 20 PID as arguments.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .