Limit the output of the TOP command to a specific process name

后端 未结 17 2508
臣服心动
臣服心动 2020-12-12 09:48

If you call the top command, you get all the running processes. But how can I limit the output only to a certain process name like \"java\"?

I\'ve

相关标签:
17条回答
  • 2020-12-12 10:05

    I came here looking for the answer to this on OSX. I ended up getting what I wanted with bash and awk:

    topfiltered() {
      [[ -z "$1" ]] && return
      dump="/tmp/top_dump"
      rm -f "$dump"
      while :; do
        clear
        [[ -s "$dump" ]] && head -n $(( $LINES - 1 )) "$dump"
        top -l 1 -o cpu -ncols $(( $COLUMNS / 8 )) | awk -v p="$(pgrep -d ' ' $@)" '
            BEGIN { split(p, arr); for (k in arr) pids[arr[k]]=1 }
            NR<=12 || ($1 in pids)
        ' >"$dump"
      done
    }
    

    I loop top in logging mode and filter it with awk, building an associative array from the output of pgrep. Awk prints the first 12 lines, where line 12 is the column headers, and then every line which has a pid that's a key in the array. The dump file is used for a more watchable loop.

    0 讨论(0)
  • 2020-12-12 10:06

    Find the pids of the processes you want to monitor and then use the -p option which allows you to provide a list of pids to the top command.

    Example:

    top -p 18884 -p 18892 -p 18919
    
      PID USER     PRI  NI  SIZE  RSS SHARE STAT %CPU %MEM   TIME CPU COMMAND
    18884 user  25   0  672M  95M  9476 S     0.0  1.1   0:02   1 java
    18892 user  25   0 2280M 123M 12252 S     0.0  1.5   0:05   1 java
    18919 user  22   0 1492M 198M 28708 S     0.0  2.4   0:07   1 java
    

    (I believe you can also pass in a comma-separated list.)

    0 讨论(0)
  • 2020-12-12 10:06

    A more specific case, like I actually was looking for:

    For Java processes you can also use jps -q whereby jps is a tool from $JAVA_HOME/bin and hence should be in your $PATH.

    0 讨论(0)
  • 2020-12-12 10:11

    Using the answer from here I was able to create a one liner

    top -pid $(pgrep process_name | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ -pid /g')
    

    This works for me on MacOS 10.12 (Sierra)

    0 讨论(0)
  • 2020-12-12 10:12

    I solved my problem using:

    top -n1 -b | grep "proccess name"

    in this case: -n is used to set how many times top will what proccess
    and -b is used to show all pids

    it's prevents errors like : top: pid limit (20) exceeded

    0 讨论(0)
  • 2020-12-12 10:15

    just top -bn 1 | grep java will do the trick for you

    0 讨论(0)
提交回复
热议问题