Low Orbit Flux Logo 2 F

Linux Command - top

The linux top command shows running processes and stats in real-time. This doc is mostly based on top from procps-ng 4.0.2.

Start top:



top

Don’t show zombie or idle processes:



top -i

Sort by field:



top -o VIRT
top -o RES
top -o SHR
top -o %CPU
top -o %MEM 
top -o COMMAND

Only processes with these pids:



top -p 1257,1258

top -p $( pgrep -d ',' gnome )

Individual threads of a process:



top -Hp 1257

Only processes owned by this user:



top -u user1

Batch mode, repeat once:



top -b -n 1

h help
? help
q exit
ctrl-c exit

Memory and Meory Quadrants



memory quadrant diagram (private/shared - Anonymous / File-backed)

                                     Private | Shared
                                 1           |          2
            Anonymous  . stack               |
                       . malloc()            |
                       . brk()/sbrk()        | . POSIX shm*
                       . mmap(PRIVATE, ANON) | . mmap(SHARED, ANON)
                      -----------------------+----------------------
                       . mmap(PRIVATE, fd)   | . mmap(SHARED, fd)
          File-backed  . pgms/shared libs    |
                                 3           |          4

Options

-b batch mode, doesn’t accept input, runs until ‘-n’ iteration limit or killed
-n max iterations before ending
-d delay in seconds for refresh
-E memory scale for summary area
-e memory scale for task area

Memory scale units:

k kibibytes
m mebibytes
g gibibytes
t tebibytes
p pebibytes
e exbibytes

More options:

-H show individual threads, also threads instead of tasks at top
-h help
-O print list of fields
-o select field to sort by, +/- to specify sort order, + high to low, - low to high
-p monitor comma separated list of pids
-s secure mode
-U username or user ID ( real, effective, saved, filesystem ), use ! to negate
-u username or user ID ( effective ), use ! to negate
us time running un-niced user processes
sy time running kernel processes
ni time running niced user processes
id time spent in the kernel idle handler
wa time waiting for I/O completion
hi time spent servicing hardware interrupts
si time spent servicing software interrupts
st time stolen from this vm by the hypervisor
t switch mode, can show user, system, total percent, graph


                      a    b     c    d
           %Cpu(s):  75.0/25.0  100[ ... ]          

I Irix mode on / off

Fields

CPU usage:

Process Status - The status of the task which can be one of:

Fields:

%CPU CPU Usage
%CUC CPU Utilization ( devided by running time as percentage ), include reaped procs
%CUU CPU Utilization ( devided by running time as percentage )
%MEM Memory Usage (RES)
AGID Autogroup Identifier … more details in man page
AGNI Autogroup Nice Value ( for all procs in group )
CGNAME Control Group Name
CGROUPS Control Groups
CODE Code Size (KiB) - mem dedicated to executable code ( Text Resident Set size or TRS )
COMMAND Command Name or Command Line ( use ‘c’ to toggle between command line and name )
DATA Data + Stack Size (KiB) ( Data Resident Set or DRS ) always virtual, might not be physical
ELAPSED Elapsed Running Time
ENVIRON Environment variables
EXE Executable Path
Flags Task Flags ( scheduling flags )
GID Group Id
GROUP Group Name
LOGID Login User Id
LXC Lxc Container Name
NI Nice Value
NU Last known NUMA node
OOMa Out of Memory Adjustment Factor ( added to OOMs )( -1000 to +1000, determines which task to kill on OOM)
OOMs Out of Memory Score ( 0 to +1000, 0 never kill, 1000 always kill)
P Last used CPU (SMP)
PGRP Process Group Id
PID Process Id
PPID Parent Process Id
PR Priority ( scheduling priority, rt is real time)
PSS Proportional Resident Memory, smaps (KiB)
PSan Proportional Anonymous Memory, smaps (KiB)
PSfd Proportional File Memory, smaps (KiB)
PSsh Proportional Shmem Memory, smaps (KiB)
RES Resident Memory Size (KiB) -( non-swapped physical memory )
RSS Resident Memory, smaps (KiB)
RSan Resident Anonymous Memory Size (KiB)
RSfd Resident File-Backed Memory Size (KiB)
RSlk Resident Locked Memory Size (KiB)
RSsh Resident Shared Memory Size (KiB)
RUID Real User Id
RUSER Real User Name
S Process Status
SHR Shared Memory Size (KiB) - part of RES, may be used by other procs
SID Session Id
STARTED Start Time Interval “length of time since system boot when a process started”
SUID Saved User Id
SUPGIDS Supplementary Group IDs
SUPGRPS Supplementary Group Names
SUSER Saved User Name
SWAP Swapped Size (KiB) - mem that was swapped out after physical mem is overcommitted
TGID Thread Group Id
TIME CPU Time - total CPU time used - ‘S’ to toggle cumulative mode and show usage for dead children
TIME+ CPU Time, hundredths
TPGID Tty Process Group Id
TTY Controlling Tty
UID User Id
USED Memory in Use (KiB) - physical and swap usage ( RES + SWAP )
USER User Name - effective user name of task owner
USS Unique Set Size - non swapped physical mem usage not shared with other procs
VIRT Virtual Memory Size (KiB)
WCHAN Sleeping in Function - kernel function name that task is sleeping in
ioR I/O Bytes Read
ioRop I/O Read Operations ( syscalls, might n ot have actual physical I/O)
ioW I/O Bytes Written
ioWop I/O Write Operations ( syscalls, might n ot have actual physical I/O)
nDRT Dirty Pages Count - pages not written to aux storage - can’t be swapped out yet )
nMaj Major Page Fault Count - attepmt to read virt mem that isn’t there and need to use aux storage
nMin Minor Page Fault count - attepmt to read virt mem that isn’t there and DOESN’T need to use aux storage
vMj Major Page Fault Count Delta - Major Page Faults since last update
vMn Minor Page Fault Count Delta - Minor Page Faults since last update
nTH Number of Threads
nsCGROUP CGROUP namespace
nsIPC IPC namespace
nsMNT MNT namespace
nsNET NET namespace
nsPID PID namespace
nsTIME TIME namespace
nsUSER USER namespace
nsUTS UTS namespace

Commands

f manage fields - show screen and sort field
g choose another window
up,down, pgup, pgdn, home, end navigate
right arrow select field for repositioning
left arrow / enter commit position
d / space toggle display status
s set selected field as sort field
a/w cycle through windows
q/esc - quit ( exits to selected window )

Secure mode will dissallow doing things like killing, renicing, etc. It is also enforced for root.

GLOBAL Commands

enter / space refresh now
q quit
? / h get help
= exit display limits - basically remove all filtering and stuff
0 Zero-Suppress toggle - don’t show zero for some fields
A Alternate-Display-Mode toggle
B :Bold-Disable/Enable toggle
d / s Change-Delay-Time-interval - can be positive, fractional, or zero
E Enforce-Summary-Memory-Scale in Summary Area - cycle between KiB - EiB
e Enforce-Task-Memory-Scale in Task Area - cycle between KiB - EiB
g Choose-Another-Window/Field-Group - select window, prompts for number 1-4
H Threads-mode toggle - show threads instead of summation
I Irix/Solaris-Mode toggle
k Kill-a-task - prompted for PID and signal
r Renice-a-Task - prompted for PID and nice value
W Write-the-Configuration-File - save settings in config file
X Extra-Fixed-Width - adjust width for some columns
Y Inspect-Other-Output - prompt for PID, show info on other screen

Used to inspect in the pager ( for Y command ), needs configuration in config file ( “adding INSPECT entries” ):

key function
= alternate status-line, file or pipeline
/ find, equivalent to `L’ locate
n find next, equivalent to `&’ locate next
Space scroll down, equivalent to PgDn
b scroll up, equivalent to PgUp
g first line, equivalent to Home
G last line, equivalent to End

More commands:

Z Change-Color-Mapping - prompts for keys to change collors ( select color, select targert )
^G Display-Control-Groups (Ctrl key + `g’) ( for first proc listed )
^K Display-Cmdline (Ctrl key + `k’) ( for first proc listed )
^N Display-Environment (Ctrl key + `n’) ( for first proc listed )
^P Display-Namesspaces (Ctrl key + `p’) ( for first proc listed )
^U Display-Supplementary-Groups (Ctrl key + `u’) ( for first proc listed )
^L Logged-Messages (Ctrl key + `l’) - show recetn messges
^R Renice-an-Autogroup (Ctrl key + `r’)

SUMMARY AREA Commands

C Show-scroll-coordinates toggle
l Load-Average/Uptime toggle
m Memory/Swap-Usage toggle
t Task/Cpu-States toggle - summary lines
1 Single/Separate-Cpu-States toggle
2 NUMA-Nodes/Cpu-Summary toggle
3 Expand-NUMA-Node
4 Display-Multiple-Elements-Adjacent toggle
5 Display-P-Cores-and-E-Cores toggle
! Combine-Cpus-Mode toggle

TASK AREA Commands

J Justify-Numeric-Columns toggle
j Justify-Character-Columns toggle
b Bold/Reverse toggle
x Column-Highlight toggle - for sort field - column turns bold - if color mode (‘z’) col also is colored
y Row-Highlight toggle - running tasks turn bold, if color mode (‘z’) col also is colored
z Color/Monochrome toggle - conflicts with colors picked with “Z” ( capital )
c Command-Line/Program-Name toggle
F Maintain-Parent-Focus toggle - in forest mode, select top task and pin it to the top basically
f Fields-Management - ….
O or o Other-Filtering - setup task filtering ….. more info ….
S Cumulative-Time-Mode toggle - count CPU time of dead children or not
U or u Show-Specific-User-Only - prompt to filter by user: ex: ‘user1’ or ‘!user1’
V Forest-View-Mode toggle - order procs by parent
v Hide/Show-Children toggle - show / hide children of top most ( selected ) proc
^E Scale-CPU-Time-fields (Ctrl key + `e’)
i Idle-Process toggle - show / don’t show idle tasks
n or # Set-Maximum-Tasks

Sort keys from old top: ?????:

command sorted-field supported
A start time (non-display) No
M %MEM Yes
N PID Yes
P %CPU Yes
T TIME+ Yes
< Move-Sort-Field-Left
> Move-Sort-Field-Right
R Reverse/Normal-Sort-Field toggle

Alternate display mode

( some commands will behave different in alternate display mode )

A Alternate-Display-Mode toggle - switch between full screen and alternate display mode
- (dash) hide current window
_ (underscore) inverse which windows are hidden or hide all_
= force current window task display visible and clear all filters resetting window
+ same but for all windows
a next window
w previous window
G change window name ( will prompt )
g change current window ( will prompt )

Scrolling ( alternate and normal mode ):

Up,PgUp,Down,PgDn,Left,Right,Home,End Navigate
C show scroll coordinates

Searching ( alternate and normal mode ):

L search for case sensitive string
& locate next

Filtering

O case sensitive filter ( will prompt )
o case insensitive filter ( will prompt )
ctrl O show active filters
= reset filters in current window
+ reset filters for all windows

Example filter:



USER=user1
PID>100
!USER=user1
!USER=Debian-+
RES>100
nTH>1

Config files:

W save current config to file to .config/procps/toprc ( legacy paths are different )

Inspect Entires

Three elements, tab separated:

.type literal file' or pipe’
.name selection shown on the Inspect screen
.fmts string representing a path or command


# pipe ^I Sockets ^I lsof -n -P -i 2>&1
pipe ^I Open Files ^I lsof -P -p %d 2>&1
file ^I NUMA Info ^I /proc/%d/numa_maps
pipe ^I Log ^I tail -n100 /var/log/syslog | sort -Mr

pipe ^I Trace ^I /usr/bin/strace -p %d 2>&1

SYSTEM Restrictions File: /etc/toprc

Should contain these two lines:



s        # line 1: secure mode switch
5.0      # line 2: delay interval in seconds

This file will have the following effect:



"""
      They will not be able to issue the following commands.
           k        Kill a task
           r        Renice a task
           d or s   Change delay/sleep interval  
"""           
  

Env variable:



"""
       LIBPROC_HIDE_KERNEL
              This  will  prevent  display  of any kernel threads and exclude such processes from the
              summary area Tasks/Threads counts.
"""  
  
export LIBPROC_HIDE_KERNEL=asdf