Skip to content

top

top命令简介

运行系统的动态实时视图。它可以显示系统摘要信息以及当前由Linux内核管理的进程或线程列表;
操作提供了有限的交互界面,也为个人配置提供了更广泛的界面;

top区域介绍

# top
top - 15:18:24 up 193 days, 11:54,  3 users,  load average: 0.28, 0.59, 0.65
Tasks: 236 total,   2 running, 234 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.1 us,  0.0 sy,  0.0 ni, 99.8 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
KiB Mem : 16266080 total,  2152324 free,  5184964 used,  8928792 buff/cache
KiB Swap:  8257532 total,  7057188 free,  1200344 used.  9784868 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                                                                                                                                         
10497 root      20   0 9974972   1.1g   4732 S   0.7  6.9   2938:33 java                                                                                                                                                            
17197 root      20   0  162148   2468   1596 R   0.7  0.0   0:00.08 top                                                                                                                                                             
    9 root      20   0       0      0      0 R   0.3  0.0 345:41.52 rcu_sched                                                                                                                                                       
 3289 root      20   0       0      0      0 S   0.3  0.0 937:03.84 xfsaild/dm-0                                                                                                                                                    
15989 root      20   0       0      0      0 S   0.3  0.0   0:00.25 kworker/5:0                                                                                                                                                     
    1 root      20   0  193936   4512   2520 S   0.0  0.0 301:57.28 systemd

概览区域

top - 
// 系统当前时间存活时间用户数
15:18:24 //系统当前时间
up 193 days, 11:54,  //系统在线时间
3 users,  //当前登录用户数

// 5分钟、10分钟、15分钟负载平均值
// load average数据是每隔5秒钟检查一次活跃的进程数,然后按特定算法计算出的数值
// 如果这个数除以逻辑CPU的数量,结果高于5的时候就表明系统在超负荷运转了
load average: 0.28, 0.59, 0.65

// Tasks:    总进程数或总线程数,取决于是否开启线程模式
// running:  运行进程数
// sleeping:休眠进程数
// stopped:  停止进程数
// zombie:   僵尸进程数
Tasks: 236 total,   2 running, 234 sleeping,   0 stopped,   0 zombie

// us:      user,用户空间占用CPU的百分比
// sy:       system,内核空间百分比
// ni:       nice,改变过优先级的进程占用CPU的百分比
        #nice 值,一般表示静态优先级,范围为 -20 ~ 19,一共 40 (NICE_WIDTH) 个档次.
        #其值越小,表示优先级越高。另外,实时进程下的优先级设置似乎与该值无关,故该值仅影响非实时进程。
// id:       idle,空闲百分比
// wa:       IO-wait,IO等待百分比
// hi:       硬中断百分比
// si:       软中断百分比
// st:       当前虚拟机中的cpu周期被物理机中的实例偷走的比例。
%Cpu(s):  0.1 us,  0.0 sy,  0.0 ni, 99.8 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st


// 内存使用情况,默认Mb为单位,交互命令按E切换单位,交换空间使用变动证明内存已不足使用。
// total:       总内存
// free:        剩余内存
// used:       已用内存
// buff/cache: 缓冲与缓存
KiB Mem : 16266080 total,  2152324 free,  5184964 used,  8928792 buff/cache
KiB Swap:  8257532 total,  7057188 free,  1200344 used.  9784868 avail Mem 



// 不管如何设置优先级,实时进程对于 CPU 的抢占能力一定大于非实时进程
// 实时进程:SCHED_RR
// 非实时进程:SCHED_OTHER
// 动态优先级: 进程优先级的取值范围由一个宏定义表示: MAX_PRIO,它的值为140,所以我们最终能看到的优先级应该是 0 ~ 139 之间的一些数。有两种状态量都能表示这种优先级
显示名称    功能
us  未调整优先级的用户进程的运行cpu时间
sy  内核进程的运行cpu时间
ni  已调整优先级的用户进程的运行cpu时间
id  内核空闲cpu时间
wa  等待IO完成的cpu时间
hi  硬件中断cpu时间
si  软件中断cpu时间
st  当前vm被hypervisor偷去的cpu时间
PR: Priority 动态优先级
1、priority的值在内核的调度器上表现是会变化的,所以也叫做动态优先级,是进程内核态的一个概念
2、范围从0到139。值越小,优先级越高,越容易被调度器执行。0-99,实时进程(rt)优先级范围。100-139,非实时进程
3、取值rt表示实时进程

NI: Nice Value 优先值、静态优先级
1、nice值也叫做静态优先级,是一个进程用户态的一个概念,除非我们用renice去改它,否则它是不变的。通过NI来影响PR
1、取值范围是-20至19,一共40个级别。负值表示高优先级,正值表示低优先级
2、设置nice值的命令有:nice -n 10 bash ## 启动并设置nice值、renice 10 -p pid ## 重新调整进程nice值
 
VIRT:virtual memory usage 虚拟内存
1、进程“需要的”虚拟内存大小,包括进程使用的库、代码、数据等
2、假如进程申请100m的内存,但实际只使用了10m,那么它会增长100m,而不是实际的使用量
 
RES:resident memory usage 常驻内存
1、进程当前使用的内存大小,但不包括swap out
2、包含其他进程的共享
3、如果申请100m的内存,实际使用10m,它只增长10m,与VIRT相反
4、关于库占用内存的情况,它只统计加载的库文件所占内存大小
 
SHR:shared memory 共享内存
1、除了自身进程的共享内存,也包括其他进程的共享内存
2、虽然进程只使用了几个共享库的函数,但它包含了整个共享库的大小
3、计算某个进程所占的物理内存大小公式:RES – SHR
4、swap out后,它将会降下来
 
DATA
1、真正的该程序要求的数据空间,是真正在运行中要使用的。

表头

PID USER      
PR      //Priority 动态优先级
NI    //Nice Value 优先值、静态优先级
VIRT   //virtual memory usage 虚拟内存 
RES    //resident memory usage 常驻内存
SHR S  //shared memory 共享内存
%CPU 
%MEM     
TIME+ 
COMMAND
// 可以理解为%CPU为:%cpu是表示单核cpu的占用率,而不是占用所有 cpu 的占用率. 即如果我们是32核 cpu,那么3200% 才是最高的cpu利用率

// shift i 切换为显示cpu占用率

任务区域

任务区域就是基于表头的列表数据展示

top命令行参数

选项 功能
-h/-v 帮助/版本 展示帮助文档和版本,之后退出
-b 批处理模式 使用批处理模式启动top,这种启动方式可以有效地把top的结果输出到程序或文件。在这种模式下,top不会接收输入,且根据-n设置的迭代次数执行完毕后或者主动杀掉进程才会使当前top进程终止。
-c 命令行/程序名切换 top开启后显示的是上一次使用'c'功能生效的效果的反面效果,如果上一次是命令行,这一次显示的就是程序名
-d 延迟时间间隔:-d ss.t(ss秒.10分之t) 设置屏幕刷新时间间隔,覆盖个人配置或开机默认配置。这个参数之后可以通过'd'或's'交互命令修改。分数形式是可接受的,但负数是不能接受的。但是上述修改在安全模式下是禁止的,除非使用root用户执行。
-E 扩展内存展示形式:-E k|m|g|t|p|e 设置内存单位: k - kibibytes m - mebibytes g - gibibytes t - tebibytes p - pebibytes e - exbibytes 这个值可以用'E'切换
-H 线程模式 展示独立线程。在不使用这个参数时,每个进程将展示所有线程的一个总值。这个值可以用'H'切换
-i 空闲进程切换 top开启后显示的是上一次使用'i'功能生效的效果的反面效果,当这个切换状态是'关闭'时,从上一次展示到现在没有使用任何CPU的任务不会被展示。
-n 迭代限制次数:-n 数字 设置最大迭代次数,在执行次数等于这个数字之后top退出。
-o 覆盖排序字段:-o 字段名 指定将对任务进行排序的字段的名称,与配置文件中反映的内容无关。你也可以在字段前加一个'+'或'-','+'的作用是降序,'-'是升序。 这个选项是支持自动/脚本化批处理模式的基础。
-O 输出字段名 这个选项作为上边'-o'的补充。会使top在不同的行打印每一个字段名,之后退出。这些字段名属于NLS(国家语言支持)翻译。
-p 监视进程ID模式:-pN1 -pN2 ... 或 -pN1,N2,N3 ... 只展示指定ID的进程。这个模式可以接受最多20个进程id,可以使用用逗号分隔的列表。 为0的进程id会被视为top本身的进程id。 这个模式只能是命令行模式,如果想切换到其他模式,应该退出然后重启top。 -p, -u, -U 不能同时使用。
-s 安全模式 强制使用安全模式启动top,即使是root用户。这个模式使用系统配置文件控制的更好。
-S 累计时间切换 top开启后显示的是上一次使用'S'功能生效的效果的反面效果,当它是开启时,展示每个进程和它们的被杀掉的子进程的cpu时间。
-u/-U 用户筛选模式:-u | -U 数字或名字 只展示用户id或用户名匹配给定参数的进程。'-u' 匹配有效用户,'-U' 匹配任何用户(真实的、有效的、已存的或文件系统) 在用户id或用户名前加上前缀'!','!'表示非。 -p, -u, -U 不能同时使用。
-w 输出宽度覆盖:-w [ 数字 ] 在批处理模式,如果没有参数,top会使用环境变量 COLUMNS= 和 LINES= 作为格式来输出。另外,宽度会固定为512列。列数可以通过参数配置为任意数值(不能大于512),但是行数没有限制。 在普通模式,如果没有参数,top会尝试使用环境变量 COLUMNS= 和 LINES= 作为格式来输出。列数可以通过参数配置而减少,不能增加。只要不是在批处理模式,终端的展示尺寸大小就不能延长。 提示:只要不使用这个命令行选项,top展示的尺寸只跟终端有关。
-1 总体/分别显示CPU状态切换 top开启后显示的是上一次使用CPU状态功能生效的效果的反面效果。或者是所有cpu信息在一行显示,或者是每一个cpu分别在独立的行显示。
## 常用选项
-p pid   ## 只显示pid进程及其子进程的信息。监视多个则为 -p N1,N2,N3...
-u user  ## 只显示user用户启动的进程。
-d secs  ## 设置显示更新时间间隔为secs秒。默认为3秒。当然用户可以使用s交互命令来改变之。
-1       ## 列出所有CPU的摘要信息。
-H       ## 多线程模式,按线程划分每行。当然用户可以使用H交互命令来改变之。

-n count ## 设置显示次数为count次,然后退出。
-c       ## 显示完整的命令行,而不截断。
-q       ## 该选项将使top没有任何延迟的进行刷新。如果调用程序有超级用户权限,那么top将以尽可能高的优先级运行。
-S       ## 累积模式,连续显示多次更新结果。
-s       ## 安全模式,这将去除交互命令所带来的潜在危险。
-i       ## 忽略空闲和僵死进程。
-b       ## 以批处理模式操作,启动后不显示交互命令提示符,方便将结果输出到其它程序或文件。

top终端操作

左右键;
m c操作;
1 2 3操作;
shift i 操作;

top命令的常用参数


top man手册查看

TOP(1)                                                                                                   User Commands                                                                                                   TOP(1)

NAME
       top - display Linux processes

SYNOPSIS
       top -hv|-bcHiOSs -d secs -n max -u|U user -p pid -o fld -w [cols]

       The traditional switches `-' and whitespace are optional.

DESCRIPTION
       The  top  program provides a dynamic real-time view of a running system.  It can display system summary information as well as a list of processes or threads currently being managed by the Linux kernel.  The types of
       system summary information shown and the types, order and size of information displayed for processes are all user configurable and that configuration can be made persistent across restarts.

       The program provides a limited interactive interface for process manipulation as well as a much more extensive interface for personal configuration  --  encompassing every aspect of its operation.  And while  top  is
       referred  to  throughout this document, you are free to name the program anything you wish.  That new name, possibly an alias, will then be reflected on top's display and used when reading and writing a configuration
       file.

OVERVIEW
   Documentation
       The remaining Table of Contents

           1. COMMAND-LINE Options
           2. SUMMARY Display
              a. UPTIME and LOAD Averages
              b. TASK and CPU States
              c. MEMORY Usage
           3. FIELDS / Columns Display
              a. DESCRIPTIONS of Fields
              b. MANAGING Fields
           4. INTERACTIVE Commands
              a. GLOBAL Commands
              b. SUMMARY AREA Commands
              c. TASK AREA Commands
                 1. Appearance
                 2. Content
                 3. Size
                 4. Sorting
              d. COLOR Mapping
           5. ALTERNATE-DISPLAY Provisions
              a. WINDOWS Overview
              b. COMMANDS for Windows
              c. SCROLLING a Window
              d. SEARCHING in a Window
              e. FILTERING in a Window
           6. FILES
              a. SYSTEM Configuration File
              b. PERSONAL Configuration File
              c. ADDING INSPECT Entries
           7. STUPID TRICKS Sampler
              a. Kernel Magic
              b. Bouncing Windows
              c. The Big Bird Window
              d. The Ol' Switcheroo
           8. BUGS, 9. HISTORY Former top, 10. AUTHOR, 11. SEE Also

   Operation
       When operating top, the two most important keys are the help (h or ?)  key and quit ('q') key.  Alternatively, you could simply use the traditional interrupt key (^C) when you're done.

       When started for the first time, you'll be presented with these traditional elements on the main top screen: 1) Summary Area; 2) Fields/Columns Header; 3) Task Area.  Each of these will be explored  in  the  sections
       that follow.  There is also an Input/Message line between the Summary Area and Columns Header which needs no further explanation.

       The  main  top screen is generally quite adaptive to changes in terminal dimensions under X-Windows.  Other top screens may be less so, especially those with static text.  It ultimately depends, however, on your par  ticular window manager and terminal emulator.  There may be occasions when their view of terminal size and current contents differs from top's view, which is always based on operating system calls.

       Following any re-size operation, if a top screen is corrupted, appears incomplete or disordered, simply typing something innocuous like a punctuation character or cursor  motion  key  will  usually  restore  it.   In
       extreme cases, the following sequence almost certainly will:
              key/cmd  objective
              ^Z       suspend top
              fg       resume top
              <Left>   force a screen redraw (if necessary)

       But if the display is still corrupted, there is one more step you could try.  Insert this command after top has been suspended but before resuming it.
              key/cmd  objective
              reset    restore your terminal settings

       Note:  the  width  of top's display will be limited to 512 positions.  Displaying all fields requires approximately 250 characters.  Remaining screen width is usually allocated to any variable width columns currently
       visible.  The variable width columns, such as COMMAND, are noted in topic 3a. DESCRIPTIONS of Fields.  Actual output width may also be influenced by the -w switch, which is discussed in topic 1. COMMAND-LINE Options.

       Lastly, some of top's screens or functions require the use of cursor motion keys like the standard arrow keys plus the Home, End, PgUp and PgDn keys.  If your terminal or emulator does not  provide  those  keys,  the
       following combinations are accepted as alternatives:
              key      equivalent-key-combinations
              Up       alt + \      or  alt + k
              Down     alt + /      or  alt + j
              Left     alt + <      or  alt + h
              Right    alt + >      or  alt + l (lower case L)
              PgUp     alt + Up     or  alt + ctrl + k
              PgDn     alt + Down   or  alt + ctrl + j
              Home     alt + Left   or  alt + ctrl + h
              End      alt + Right  or  alt + ctrl + l

       The  Up and Down arrow keys have special significance when prompted for line input terminated with the <Enter> key.  Those keys, or their aliases, can be used to retrieve previous input lines which can then be edited
       and re-input.  And there are four additional keys available with line oriented input.
              key      special-significance
              Up       recall older strings for re-editing
              Down     recall newer strings or erase entire line
              Insert   toggle between insert and overtype modes
              Delete   character removed at cursor, moving others left
              Home     jump to beginning of input line
              End      jump to end of input line

   Startup Defaults
       The following startup defaults assume no configuration file, thus no user customizations.  Even so, items shown with an asterisk (`*') could be overridden through the command-line.  All are explained in detail in the
       sections that follow.

           Global-defaults
              A - Alt display      Off (full-screen)
            * d - Delay time       1.5 seconds
            * H - Threads mode     Off (summarize as tasks)
              I - Irix mode        On  (no, `solaris' smp)
            * p - PID monitoring   Off (show all processes)
            * s - Secure mode      Off (unsecured)
              B - Bold enable      On  (yes, bold globally)
           Summary-Area-defaults
              l - Load Avg/Uptime  On  (thus program name)
              t - Task/Cpu states  On  (1+1 lines, see `1')
              m - Mem/Swap usage   On  (2 lines worth)
              1 - Single Cpu       Off (thus multiple cpus)
           Task-Area-defaults
              b - Bold hilite      Off (use `reverse')
            * c - Command line     Off (name, not cmdline)
            * i - Idle tasks       On  (show all tasks)
              J - Num align right  On  (not left justify)
              j - Str align right  Off (not right justify)
              R - Reverse sort     On  (pids high-to-low)
            * S - Cumulative time  Off (no, dead children)
            * u - User filter      Off (show euid only)
            * U - User filter      Off (show any uid)
              V - Forest view      On  (show as branches)
              x - Column hilite    Off (no, sort field)
              y - Row hilite       On  (yes, running tasks)
              z - color/mono       On  (show colors)

1. COMMAND-LINE Options
       The command-line syntax for top consists of:

         -hv|-bcHiOSs -d secs -n max -u|U user -p pid -o fld -w [cols]

       The typically mandatory switch ('-') and even whitespace are completely optional.

       -h | -v  :Help/Version
            Show library version and the usage prompt, then quit.

       -b  :Batch-mode operation
            Starts  top  in Batch mode, which could be useful for sending output from top to other programs or to a file.  In this mode, top will not accept input and runs until the iterations limit you've set with the `-n'
            command-line option or until killed.

       -c  :Command-line/Program-name toggle
            Starts top with the last remembered `c' state reversed.  Thus, if top was displaying command lines, now that field will show program names, and visa versa.  See the `c' interactive command for additional  infor‐
            mation.

       -d  :Delay-time interval as:  -d ss.t (secs.tenths)
            Specifies the delay between screen updates, and overrides the corresponding value in one's personal configuration file or the startup default.  Later this can be changed with the `d' or `s' interactive commands.

            Fractional seconds are honored, but a negative number is not allowed.  In all cases, however, such changes are prohibited if top is running in Secure mode, except for root (unless the `s' command-line option was
            used).  For additional information on Secure mode see topic 6a. SYSTEM Configuration File.

       -H  :Threads-mode operation
            Instructs top to display individual threads.  Without this command-line option a summation of all threads in each process is shown.  Later this can be changed with the `H' interactive command.

       -i  :Idle-process toggle
            Starts top with the last remembered `i' state reversed.  When this toggle is Off, tasks that have not used any CPU since the last update will not be displayed.  For additional information regarding  this  toggle
            see topic 4c. TASK AREA Commands, SIZE.

       -n  :Number-of-iterations limit as:  -n number
            Specifies the maximum number of iterations, or frames, top should produce before ending.

       -o  :Override-sort-field as:  -o fieldname
            Specifies  the name of the field on which tasks will be sorted, independent of what is reflected in the configuration file.  You can prepend a `+' or `-' to the field name to also override the sort direction.  A
            leading `+' will force sorting high to low, whereas a `-' will ensure a low to high ordering.

            This option exists primarily to support automated/scripted batch mode operation.

       -O  :Output-field-names
            This option acts as a form of help for the above -o option.  It will cause top to print each of the available field names on a separate line, then quit.  Such names are subject to nls translation.

       -p  :Monitor-PIDs mode as:  -pN1 -pN2 ...  or  -pN1,N2,N3 ...
            Monitor only processes with specified process IDs.  This option can be given up to 20 times, or you can provide a comma delimited list with up to 20 pids.  Co-mingling both approaches is permitted.

            A pid value of zero will be treated as the process id of the top program itself once it is running.

            This is a command-line option only and should you wish to return to normal operation, it is not necessary to quit and restart top  --  just issue any of these interactive commands: `=', `u' or `U'.

            The `p', `u' and `U' command-line options are mutually exclusive.

       -s  :Secure-mode operation
            Starts top with secure mode forced, even for root.  This mode is far better controlled through the system configuration file (see topic 6. FILES).

       -S  :Cumulative-time toggle
            Starts top with the last remembered `S' state reversed.  When Cumulative time mode is On, each process is listed with the cpu time that it and its dead children have used.  See the `S'  interactive  command  for
            additional information regarding this mode.

       -u | -U  :User-filter-mode as:  -u | -U number or name
            Display only processes with a user id or user name matching that given.  The `-u' option matches on  effective user whereas the `-U' option matches on any user (real, effective, saved, or filesystem).

            Prepending an exclamation point ('!') to the user id or name instructs top to display only processes with users not matching the one provided.

            The `p', `u' and `U' command-line options are mutually exclusive.

       -w  :Output-width-override as:  -w [ number ]
            In  Batch  mode,  when  used without an argument top will format output using the COLUMNS= and LINES= environment variables, if set.  Otherwise, width will be fixed at the maximum 512 columns.  With an argument,
            output width can be decreased or increased (up to 512) but the number of rows is considered unlimited.

            In normal display mode, when used without an argument top will attempt to format output using the COLUMNS= and LINES= environment variables, if set.  With an argument, output width can  only  be  decreased,  not
            increased.  Whether using environment variables or an argument with -w, when not in Batch mode actual terminal dimensions can never be exceeded.

            Note: Without the use of this command-line option, output width is always based on the terminal at which top was invoked whether or not in Batch mode.