How to Monitor Running Linux Processes

Here’s a comprehensive guide to the top command in Linux/Unix, including practical examples for monitoring system resources, managing processes, and customizing the display:

Alby Andersen

These examples demonstrate how to use top both interactively and non-interactively, enabling you to monitor system performance, filter by user, focus on specific processes, and customize the display for your needs.


Basic top Usage

  1. Start top
    Open the default system monitor:
   top
  1. Update Interval
    Refresh the display every N seconds (e.g., 2 seconds):
   top -d 2

Process Sorting

  1. Sort by CPU Usage
    Press P (Shift + p) while top is running.
  2. Sort by Memory Usage
    Press M (Shift + m).
  3. Sort by Process ID (PID)
    Press N.

Filtering Processes

  1. Show Processes for a Specific User
    Press u, then enter the username.
    Example:
   top -u apache
  1. Monitor a Single Process
    Track a process by PID:
   top -p 1234
  1. Highlight Running Processes
    Press R to toggle highlighting.

Batch Mode (Scripting)

  1. Run top Once and Exit
   top -n 1 -b
  1. Save Output to a File
    bash top -n 3 -b > top_log.txt

Customizing the Display

  1. Toggle Full Command Path
    Press c to show the full command line.
  2. Add/Remove Columns
    Press f to select fields (e.g., PPID, priority).
  3. Toggle Colors
    Press z.
  4. Hide Idle Processes
    Press i to show only active tasks.

Process Management

  1. Kill a Process
    Press k, then enter the PID and signal (default: 15 for SIGTERM).
    Example: PID to kill: 1234 Signal: 9 # SIGKILL
  2. Renice a Process
    Press r, then enter the PID and new priority (e.g., -15 to 19).

Advanced Examples

  1. Monitor Threads
    Show threads instead of processes: top -H
  2. Show Cumulative CPU Time
    Press S to toggle cumulative mode.
  3. Check Load Average
    Look at the load average in the header (1/5/15-minute averages).
  4. Tree View
    Press V to show parent-child process hierarchy.

Key Interactive Commands

ShortcutAction
hHelp menu
qQuit
WSave current layout to ~/.toprc
lToggle load average display
tToggle task/cpu stats
1Show individual CPU cores

Common Use Cases

  • Identify CPU Hogs: Sort by CPU (P) and check %CPU column.
  • Find Memory Leaks: Sort by memory (M) and monitor %MEM.
  • Kill Zombie Processes: Look for Z in the STAT column.
  • Check I/O Wait: Look at %wa in the CPU summary line.

Pro Tips

  • Use shift + > or < to change the sort field dynamically.
  • Combine with grep for quick filtering:
  top -b -n 1 | grep "nginx"
  • For a modern alternative, try htop (sudo apt install htop).
Share This Article