1

I am trying to figure out how to get the top k number of processes in a linux shell. Obviously the first thing that popped into my head is top, but it does not seem to have any parameter to specify the number of processes to print.

Using batch mode and number of iterations parameters, I can get it to produce one iteration of all the processes and store the output, but I cannot find a way to abridge the list to a certain number. (Granted I could just get the whole list and crop it off, but the system I am using it on has 27000 processes running, so it takes a few seconds to retrieve the list).

Example:

>top -b -n1
>... (lots more processes here)
>26416 mcm101    20   0  4188  176   96 S  0.0  0.0   0:00.00 character_count
>26604 root      20   0  180m 5684 3532 S  0.0  0.0   0:00.54 sshd
>26616 pwf7      20   0  105m 1792 1432 S  0.0  0.0   0:00.10 bash

What I want is something like this:

>top k
>1 mcm101    20   0  4188  176   96 S  0.0  0.0   0:00.00 character_count
>2 pwf7      20   0  105m 1792 1432 S  0.0  0.0   0:00.10 bash
>... (more processes here)
>k root      20   0  180m 5684 3532 S  0.0  0.0   0:00.54 sshd

Does anyone know how to use top or any other command(s) to achieve this result?

4

1 に答える 1

2

これはどう:

top -b -n1 | grep '^ *[0-9]' | head -n $k

topすべてのプロセスを CPU 使用率順にgrep出力し、出力から数字で始まる行 (つまり、PID で始まる行) を選択し、その出力からhead最初のk行を出力します。

于 2013-02-09T21:01:17.780 に答える