Top

A Linux User Reference

Search tips
  • search ignores words that are less than 4 characters in length
  • searches are case insensitve
  • if a search does not return anything try it in Boolean mode then Query expansion mode by checking the appropriate radio button e.g. searching for 'cron' in just the Administration category returns nothing - presumably because the 50% threshold is reached. Boolean mode ignores this threshold so a search for 'cron' returns several hits
  • in Boolean mode preceding a word with a '+' means the result must include that word, a '-' means it must not
  • in Boolean mode '+crontab -anacron' means match articles about crontab that DO NOT mention anacron
  • to match a phrase e.g. 'manage system' check the Boolean mode radio button and enclose the phrase in quotes "some phrase ..."
  • in Query expansion mode the search context is expanded beyond the keywords you entered - relevancy of hits may well be degraded

THE SHELL

Process and signals

  • A process
    • For want of a better definition a process is a program or thread that has started but has yet to exit.
    • Processes have attributes.
    Attribute Description
    LIFETIME Length of time taken to execute, start to exit
    ID Every process has its own id (PID)
    PRIVELEGES Every process has privileges based on its user (UID) and group (GID)
    PARENT Every process has a parent process (PPID) except init the first process which has a PPID=1
    ENVIRONMENT Local and global variables, all child processes inherit their environment from the parent
    CWD Current working directory is the default directory associated with each process
  • How long has the system been running
    /usr/bin/uptime

    'uptime' gives a one line display conatining the current time, how long the system has been running, how many users are currently logged on and the system load averages for the past 1, 5, and 15 minutes.

    uptime [-V]
    

    Display how long system has been up for and command version

    $ uptime
     15:11:10 up  3:33,  4 users,  load average: 0.12, 0.20, 0.15
    
    $ uptime -V
    procps version 3.2.7
    
    mark@mark-Lenovo-G585 ~ $ uptime -V
    uptime from procps-ng 3.3.3
    
  • Display system memory usage
    /usr/bin/free

    Displays the total amount of free and used physical and swap memory in the system along with the buffers used by the kernel.

    $ free --help
    
    Usage:
     free [options]
    
    Options:
     -b, --bytes         show output in bytes
     -k, --kilo          show output in kilobytes
     -m, --mega          show output in megabytes
     -g, --giga          show output in gigabytes
         --tera          show output in terabytes
     -h, --human         show human readable output
         --si            use powers of 1000 not 1024
     -l, --lohi          show detailed low and high memory statistics
     -o, --old           use old format (no -/+buffers/cache line)
     -t, --total         show total for RAM + swap
     -s N, --seconds N   repeat printing every N seconds
     -c N, --count N     repeat printing N times
    
          --help    display this help text
     -V, --version  output version information and exit
    

    Display memory usage

    $ free
                 total       used       free     shared    buffers     cached
    Mem:       3602740     891084    2711656          0      81432     487020
    -/+ buffers/cache:     322632    3280108
    Swap:     15626236          0   15626236
    

    Display memory usage and give a total

    $ free -t
                 total       used       free     shared    buffers     cached
    Mem:       3602740     891132    2711608          0      81432     487032
    -/+ buffers/cache:     322668    3280072
    Swap:     15626236          0   15626236
    Total:    19228976     891132   18337844
    
  • Display all current processes
    /bin/ps

    Displays all current processes to stdout, many options (see man page), some common'ish ones below - output truncated.

    $ ps --help
    
    Usage:
     ps [options]
    
     Try 'ps --help <simple|list|output|threads|misc|all>'
      or 'ps --help <s|l|o|t|m|a>'
     for additional help text.
    
    For more details see ps(1).
    
    $ ps --help simple
    
    Usage:
     ps [options]
    
    Basic options:
     -A, -e               all processes
     -a                   all with tty, except session leaders
      a                   all with tty, including other users
     -d                   all except session leaders
     -N, --deselect       negate selection
      r                   only running processes
      T                   all processes on this terminal
      x                   processes without controlling ttys
    

    Man page examples:

    To see every process on the system using standard syntax

    ps -e
    ps -ef
    ps -eF
    ps -ely
    

    To see every process on the system using BSD syntax

    ps ax
    ps axu
    

    To print a process tree

    ps -ejH
    ps axjf
    

    To get info about threads

    ps -eLf
    ps axms
    

    To get security info

    ps -eo euser,ruser,suser,fuser,f,comm,label
    ps axZ
    ps -eM
    

    To see every process running as root (real & effective ID) in user format

    ps -U root -u root u
    

    Print only the process IDs of syslogd

    ps -C syslogd -o pid=
    

    Print only the name of PID 42

    ps -p 42 -o comm=
    
  • Display a tree of processes
    /usr/bin/pstree

    See man page for all options.

    pstree [options]
    
    Common options:
     -a                    Show command line arguments
     -h                    Highlight current process and its ancestors
     -l                    Don't truncate long lines
     -n                    Sort output by PID
    

    Display a process tree

    $ pstree
    init---NetworkManager---dhclient
         |                |-dnsmasq
         |                |-3*[{NetworkManager}]
         |-accounts-daemon---2*[{accounts-daemon}]
         |-acpid
         .....
         |-upstart-socket-
         |-upstart-udev-br
         |-wpa_supplicant
    

    Formatting somewhat altered as DB input filters do not like the original symbols that the program outputs. Just imagine no gaps between '-'s and '|'s.

  • Monitor processes
    /usr/bin/top

    A continuous process monitor that can be run interactively or in batch mode.

    top [options]
    
    Common options:
     -b                        Batch mode
     -d <ss.tt>                Delay time (seconds:tenths)
     -n <int>                  <int> number of iterations
     -u <user>                 Monitor <user> processes
    
    Interactive command keys:
     s                         Change update delay
     h                         Help
     k                         Kill process, prompted for PID
     Ctrl & L                  Refresh screen
     q                         Quit
     r                         Renice a process, prompted for PPID
     n                         Number of processes to show
    

    Run as a batch job, in background

    $ top -b -d 2 -n 2 >> topout.txt &
    [1] 2463
    $ jobs
    [1]+  Done                    top -b -d 2 -n 2 >> topout.txt
    $ more topout.txt
    top - 23:41:44 up 30 min,  2 users,  load average: 0.03, 0.10, 0.13
    Tasks: 146 total,   1 running, 145 sleeping,   0 stopped,   0 zombie
    .....
     2418 root      20   0     0    0    0 S   0.0  0.0   0:00.76 kworker/u8:0
     2430 root      20   0     0    0    0 S   0.0  0.0   0:00.00 kworker/u8:1
    
    top - 23:41:46 up 30 min,  2 users,  load average: 0.03, 0.10, 0.13
    Tasks: 146 total,   1 running, 145 sleeping,   0 stopped,   0 zombie
    ..... 
    

    Update every 2 secs for 2 iterations appending output to file.

    Run in interactive mode

    $ top
    
    top - 23:39:58 up 28 min,  2 users,  load average: 0.08, 0.12, 0.14
    Tasks: 146 total,   1 running, 145 sleeping,   0 stopped,   0 zombie
    %Cpu(s):  1.0 us,  0.7 sy,  0.0 ni, 97.3 id,  1.0 wa,  0.0 hi,  0.0 si,  0.0 st
    KiB Mem:   3602740 total,   906044 used,  2696696 free,    82564 buffers
    KiB Swap: 15626236 total,        0 used, 15626236 free,   489416 cached
    
      PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND
     1203 root      20   0  271m  38m  20m S   1.7  1.1   1:11.48 Xorg
     1776 mark      20   0 1690m  79m  32m S   1.7  2.3   1:12.60 cinnamon
     2258 mark      20   0  586m  19m  12m S   1.0  0.6   0:15.49 gnome-terminal
      409 root      20   0     0    0    0 S   0.7  0.0   0:11.06 rts5139-polling
     2432 mark      20   0 20648 1612 1160 R   0.7  0.0   0:00.26 top
    ..... 
    
  • Run a command ignoring hangup signals
    /usr/bin/nohup

    Command usage

    $ nohup --help
    Usage: nohup COMMAND [ARG]...
      or:  nohup OPTION
    
    Run COMMAND, ignoring hangup signals.
    
          --help     display this help and exit
          --version  output version information and exit
    
    If standard input is a terminal, redirect it from /dev/null.
    If standard output is a terminal, append output to 'nohup.out' if possible,
    '$HOME/nohup.out' otherwise.
    If standard error is a terminal, redirect it to standard output.
    
    NOTE: your shell may have its own version of nohup, which usually supersedes
    the version described here.  Please refer to your shell's documentation
    for details about the options it supports.
    .....
    

    To save output to FILE

    nohup COMMAND > FILE
    
  • Process signals
    • A process's behaviour can be altered by sending it a signal.
    • A signal can be stipulated as either a name (HUP or SIGHUP) or the number associated with it (e.g. for HUP it's number is 1).
    • Common signals include ...
    Name Number Behaviour
    HUP 1 Hangup, many daemons respond by re-reading their configuration files
    INT 2 Interrupt, stop running, sent by Ctrl & C
    KILL 9 Kill, stop unconditionally
    TERM 15 Terminate nicely if possible
    CONT 18 Continue execution, starts a stopped/suspended process sent by shell when placing jobs in foreground/background
    TSTP 20 Stop executing, go to ready to resume state, sent by Ctrl & Z

    Signal overview and complete list

    $ man 7 signal
    

    See also the 'kill' command below.

  • Send a signal to a process
    /bin/kill
    • Sends a signal to a process.
    • The default signal sent by kill is TERM, to terminate the process.
    • Sends signal to all processes belonging to all listed pids
    • Lists signals, names and numbers
    kill -l [ signal ]
    kill    [ -signal | -s signal ] pid ...
    

    Send the default signal to these three processes ids (PIDs)

    # kill 1234 5678 9876
    

    List available signal names and numbers

    $ kill -l
     1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL   5) SIGTRAP
     6) SIGABRT  7) SIGBUS   8) SIGFPE   9) SIGKILL 10) SIGUSR1
    11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
    ..... 
    

    List the signal name for signals 3 and 9

    $ kill -l 3 9
    QUIT
    KILL
    

    Note. The first three letters SIG are omitted from the output. Inclusion of SIG on the command line is optional - see below.

    List the signal numbers for SIGINT SIGPWR

    $ kill -l SIGINT SIGPWR
    2
    30
    

    Various ways to kill a process - PID 1234

    # kill -kill 1234
    # kill -KILL 1234
    # kill -s kill 1234
    # kill -s KILL 1234
    # kill -9 1234
    # kill -s 9 1234
    # kill -sigkill 1234
    # kill -SIGKILL 1234
    # kill -s sigkill 1234
    # kill -s SIGKILL 1234
    
  • Kill processes by name
    /usr/bin/killall
    • It sends a signal to all processes running any of the specified commands.
    • If no signal name is specified, SIGTERM is sent.
    • A 'killall' process never kills itself but may kill other 'killall' processes.
    $ killall --help
    Usage: killall [OPTION]... [--] NAME...
           killall -l, --list
           killall -V, --version
    
      -e,--exact          require exact match for very long names
      -I,--ignore-case    case insensitive process name match
      -g,--process-group  kill process group instead of process
      -y,--younger-than   kill processes younger than TIME
      -o,--older-than     kill processes older than TIME
      -i,--interactive    ask for confirmation before killing
      -l,--list           list all known signal names
      -q,--quiet          don't print complaints
      -r,--regexp         interpret NAME as an extended regular expression
      -s,--signal SIGNAL  send this signal instead of SIGTERM
      -u,--user USER      kill only process(es) running as USER
      -v,--verbose        report if the signal was successfully sent
      -V,--version        display version information
      -w,--wait           wait for processes to die
    

    Signals can be specified either by name or by number or by option '-s'.

  • Modify a process's priority
    /usr/bin/nice
    • The niceness of a process affects its scheduling.
    • Used to run a command with a user defined niceness, ranges from -20 (most favourable) to 19 (least).
    $ nice --help
    Usage: nice [OPTION] [COMMAND [ARG]...]
    
    Run COMMAND with an adjusted niceness, which affects process scheduling.
    
      -n, --adjustment=N     add integer N to the niceness (default 10)
          --help             display this help and exit
          --version          output version information and exit
    
    NOTE: your shell may have its own version of nice, which usually supersedes
    the version described here.  Please refer to your shell's documentation
    for details about the options it supports.
    .....
    

    Show current 'niceness'

    $ nice
    0
    

    On the fence ....

    Run the find command with a nice value = -10

    # nice -n -10 find / -name 'file*' -exec ls -al {} \;
    

    In a hurry.

  • Alter a process's niceness
    /usr/bin/renice

    Command usage

    $ renice --help
    
    Usage:
     renice [-n] <priority> [-p] <pid> [<pid>  ...]
     renice [-n] <priority>  -g <pgrp> [<pgrp> ...]
     renice [-n] <priority>  -u <user> [<user> ...]
    
    Options:
     -g, --pgrp <id>        interpret as process group ID
     -h, --help             print help
     -n, --priority <num>   set the nice increment value
     -p, --pid <id>         force to be interpreted as process ID
     -u, --user <name|id>   interpret as username or user ID
     -v, --version          print version
    
    For more information, see renice(1).
    

    Renice all user mark's processes to a nice value = -1

    $ sudo renice -1 -u mark
    1000 (user ID) old priority -10, new priority -1
    
    $ nice
    -1
    

    Change priority of process ID's 987 and 32 and all processes owned by users daemon and root

    # renice +1 987 -u daemon root -p 32
    
  • Job control
    jobs
    • The ability, provided by the shell to stop, start and suspend jobs and to place them in the background or foreground.
    • A job/process is run in the background by appending an & to the end of the command.

    Displays active jobs - jobs

    A Shell builtin command. Displays active jobs.

    jobs [options] [ jobspec ... ]
    
    Common options:
     -l                List process IDs in addition to the normal information
     -r                Restrict output to running jobs
     -s                Restrict output to stopped jobs
    

    There are a number of ways to refer to a job in the shell

     %                 References a job name
     %n                References a job number where n=number
     %ce               Refers to a stopped job whose prefix is 'ce'
     %?ce              Any job containing the string 'ce' in its command line
                       If more than one job is matched an error is reported.
     %%  and %+        Refers to the shell's notion of the current job - the 
                       last job stopped while it was in the foreground or 
                       started in the background
     %-                Refers to the previous job
    

    Start a job and observe

    $ top -b -d 5 -n 100 > /dev/null &
    [1] 2804
    
    $ jobs
    [1]+  Running                 top -b -d 5 -n 100 > /dev/null &
    
    $ jobs -l
    [1]+  2804 Running                 top -b -d 5 -n 100 > /dev/null &
    
    $ kill %1
    

    a [job spec] followed by '+' or a single % with no accompanying job specificationis the shell's notion of the current job

    a [job spec] followed by '-' is the previous job

  • Place a job in the foreground, background
    fg, bg

    Shell builtin commands. 'fg' places a job in the foreground, 'bg' place' a job in the background.

    fg [jobspec]
    bg [jobspec]
    

    List current jobs

    $ jobs
    [1]+  Stopped   sudo find / -name 'file*' -exec ls -al {} \;
    

    Bring the above listed job to the foreground

    $ fg %1
    

    Put back into the background

    $ bg
    

    If no job number given, current job denoted by a '+' is selected.