Daily Linux Command: Top

<span>top</span> is a commonly used command-line tool in Linux systems for dynamically monitoring system resource usage in real-time. It displays the resource usage of various processes in the system (such as CPU and memory usage) and provides some interactive operation features.

๐Ÿ“Œ Basic Syntax

top

After running, you will see an interface similar to the following:

top - 14:30:00 up 2 days,  3:15,  1 user,  load average: 0.15, 0.08, 0.05
Tasks: 150 total,   1 running, 149 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.3 us,  1.2 sy,  0.0 ni, 96.5 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :   3945.2 total,    450.1 free,   2120.3 used,   1374.8 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   1500.5 avail Mem 

  PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
  1234 user     20   0  500000  30000   15000 S   5.6   0.7   1:23.45 firefox

๐Ÿงพ Common Functions and Parameter Descriptions

1. Default Run

top

Displays the real-time resource usage of all processes in the system.

2. Display Processes of a Specific User

top -u username

Only displays the processes of a specific user, for example:

top -u www-data

3. Sort by Memory Usage

Press the <span>M</span> key to sort by memory usage percentage.

4. Sort by CPU Usage (Default)

Press the <span>P</span> key to sort by CPU usage rate.

5. Display Threads

top -H

Can view the thread status under each process (can also switch by pressing the <span>H</span> key).

6. Set Refresh Interval (Seconds)

top -d 5

Sets the refresh interval to every 5 seconds, the default is 3 seconds.

7. Display Process of a Specific PID

top -p 1234

Only displays the process of the specified PID. Multiple PIDs can be separated by commas:

top -p 1234,5678

8. Quiet Mode (for Scripts)

top -b

Suitable for scripts or logging, exits after outputting once.

For example, save to a file:

top -b -n 1 > top_output.txt

9. Exit <span>top</span>

Press the <span>q</span> key to exit.

๐Ÿ› ๏ธ Common Interactive Commands (Key Presses During Runtime)

Key Function
<span>P</span> Sort by CPU usage
<span>M</span> Sort by memory usage
<span>T</span> Sort by running time
<span>1</span> Display usage for each CPU (multi-core)
<span>H</span> Display threads
<span>k</span> Kill process (input PID)
<span>r</span> Adjust process priority (nice value)
<span>q</span> Exit top

โœ… Example Use Cases

Check Which Process is Using the Most CPU

Run <span>top</span> and press <span>P</span> to sort.

Check the Process with the Highest Memory Usage

Run <span>top</span> and press <span>M</span> to sort.

Monitor a Specific Process

top -p $(pgrep nginx | tr '
' ',')

๐Ÿ“Œ Recommended Alternative Tools

  • <span>htop</span>: A more powerful and user-friendly alternative (requires installation).
    sudo apt install htop   # Debian/Ubuntu
    sudo dnf install htop   # Fedora
    

Leave a Comment