Linux commands
Browse topics

Watching processes with top

Version
unversioned
Review
Draft

Summary#

top shows system load and a process list that refreshes in place. Batch mode prints the same data once for a script or a log.

Syntax#

sh
top
top -b -n 1
top -p "$pid"
top -H -p "$pid"
top -b -n 1 -o %MEM

In the interactive screen, P sorts by CPU, M sorts by memory, 1 shows each CPU and q quits. -b selects batch mode and -n limits the number of refreshes. -H shows threads and -o chooses the sort field.

Example#

sh
(
  set -eu
  child=
  trap 'if [ -n "$child" ]; then
      kill "$child" 2>/dev/null || true
      wait "$child" 2>/dev/null || true
    fi' EXIT

  sleep 30 &
  child=$!
  until [ "$(ps -o comm= -p "$child")" = sleep ]; do sleep 0.1; done

  LC_ALL=C top -b -n 1 -p "$child" |
    awk -v pid="$child" '$1 == pid { print $NF; seen++ } END { print "tasks listed:", seen + 0 }'
)

Expected output#

Text
sleep
tasks listed: 1

Common mistakes#

The %CPU column in the first refresh covers a different interval from later ones, so take a second sample, for example with top -b -n 2 -d 1, before judging a busy process. By default a multithreaded process can exceed 100% because 100% means one CPU. VIRT counts mapped address space; compare RES to see resident memory. Column layout depends on the user's saved top configuration, so use ps -o when a script needs fixed columns.

Version applicability#

This entry describes top from procps-ng 4. BusyBox and macOS top accept different options and print different columns.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0