top - Linux


Overview

The top command in Linux provides a dynamic, real-time view of the processes running on a system. It displays a comprehensive overview of system resources, including CPU usage, memory utilization, and detailed information about individual processes. Primarily used for system monitoring, performance analysis, and managing tasks, it is a vital tool for system administrators and power users who need to oversee system health and optimize performance.

Syntax

The basic syntax of the top command is:

top [options]

Common Usage:

top

This will start top with its default settings and display.

Options/Flags

  • -d : Specifies the update delay; the time interval between screen updates. By default, it is set to 3 seconds.

  • -c: Displays the full command path alongside each process.

  • -i : Toggles whether idle tasks are shown; useful for focusing on active processes.

  • -n : Limits top to a set number of iterations before exiting, allowing for snapshots of the system.

  • -u : Filters the processes to those owned by the specified user.

  • -p : Targets the monitoring to specific processes based on their process ID.

  • -H: Displays threads as if they were separate processes.

Examples:

  1. Default launch:

    top
    
  2. Refresh rate set to 1 second:

    top -d 1
    
  3. Display only processes belonging to a specific user (alice):

    top -u alice
    
  4. Monitoring specific processes by PID (1234 and 5678):

    top -p 1234,5678
    
  5. Run top for 10 iterations then exit:

    top -n 10
    

Common Issues

  • High CPU usage by top itself: This can happen if the refresh interval (-d) is set very low. Adjust the interval higher to mitigate this.

  • Misinterpretation of CPU percentages: Remember that top shows CPU usage as a percentage of a single CPU. On multi-core systems, percentages can exceed 100% for processes using multiple cores.

  • Processes not visible: If you’re using user or PID filters, ensure they are correctly specified to see expected processes.

Integration

top can be combined with other commands for automated system monitoring or batch tasks:

Log top output every 10 seconds:

top -b -d 10 -n 6 >> top_output.txt

Kill a high-memory process using awk and xargs:

top -b -n 1 | awk '/^  PID USER/{y=1;next}y && $10 > 90 {system("kill -9 " $1)}'

Here, if the memory usage ($10) exceeds 90%, the process is killed.

  • htop – An interactive process viewer, considered an enhanced version of top.
  • vmstat – Reports virtual memory statistics.
  • ps – Reports a snapshot of current processes.

For further reading and more detailed information, consult the man page for top:

man top