
<span>top</span> is one of the most frequently used commands by operations engineers. It acts like an electrocardiogram for the system, allowing you to grasp the overall health of the machine within seconds. Today, we will thoroughly dissect this “classic tool that has stood the test of time”.
1. Applicable Scenarios: When to Use top?
- • ✅ Real-time Performance Monitoring: CPU, memory, and process load spikes? Use
<span>top</span>immediately to see who is causing the “trouble”. - • ✅ Quick Fault Localization: System lagging or slow response? Use
<span>top</span>to identify the “culprit” process consuming the most resources. - • ✅ Daily Inspections: A must-see for operations personnel to quickly assess the overall health of the system.
- • ✅ Resource Optimization Precursor: Before adjusting service configurations or scaling up, first use
<span>top</span>to collect baseline data. - • ✅ Learning Linux Process Management: An excellent visualization tool for beginners to understand process states and resource allocation.
📌 Tip:
<span>top</span>is suitable for “dynamic observation”; if you need a “static snapshot”, you can use it in conjunction with<span>ps</span>,<span>htop</span>(more modern), or<span>atop</span>(historical backtracking).
2. Basic Syntax Format
top [options]
Common options quick reference:
| Option | Function |
|---|---|
<span>-d <seconds></span> |
Set refresh interval (default 3 seconds) |
<span>-p <PID></span> |
Monitor only the specified process ID |
<span>-u <username></span> |
Display only processes of that user |
<span>-n <count></span> |
Automatically exit after refreshing N times (suitable for scripts) |
<span>-b</span> |
Batch mode (non-interactive, suitable for redirecting output) |
3. Basic Usage Method (Get Started in 5 Minutes)
Starting and Interface Interpretation
top
After starting, you will see an interface similar to this:
top - 17:57:00 up 10 days, 3:22, 2 users, load average: 0.15, 0.08, 0.05
Tasks: 215 total, 1 running, 214 sleeping, 0 stopped, 0 zombie
%Cpu(s): 2.3 us, 0.7 sy, 0.0 ni, 96.8 id, 0.2 wa, 0.0 hi, 0.0 si, 0.0 st
MiB Mem : 7974.5 total, 1234.2 free, 4567.8 used, 2172.5 buff/cache
MiB Swap: 2048.0 total, 2048.0 free, 0.0 used. 3123.4 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
1234 mysql 20 0 1.234g 456780 12345 S 5.6 5.7 123:45 mysqld
5678 nginx 20 0 123456 67890 5432 R 12.3 0.8 45:67 nginx
Key Area Interpretation:
- • First Line: System time, uptime, number of logged-in users, load average (1/5/15 minutes)
- • Second Line: Total number of processes, number of running/sleeping/stopped/zombie processes
- • Third Line:CPU Usage (us=user, sy=system, id=idle, wa=waiting for I/O, hi=hardware interrupt, si=software interrupt, st=stolen time – percentage of CPU time stolen by the hypervisor and allocated to other VMs)
- • Fourth and Fifth Lines:Physical Memory & Swap Partition usage (note that
<span>avail Mem</span>is the actual available memory) - • Process List: Default sorted by CPU usage:
- •
<span>PID</span>: Process ID - •
<span>USER</span>: Process owner - •
<span>PR</span>: Process kernel scheduling priority, the smaller the number, the higher the priority - •
<span>NI</span>: Static priority adjustment value of the process, used to indirectly affect<span>PR</span>(kernel priority),<span>NI</span>the smaller, the higher the process priority, default value is<span>0</span> - •
<span>VIRT</span>: Total virtual memory requested by the process - •
<span>RES</span>: Physical memory actually used by the process (excluding swap), i.e., the part loaded into physical memory - •
<span>SHR</span>: Memory portion shared with other processes,<span>SHR</span>is part of<span>RES</span>(i.e.,<span>SHR ≤ RES</span>); - •
<span>S</span>: State (R=running, S=sleeping, Z=zombie, D=uninterruptible sleep) - •
<span>%CPU</span>/<span>%MEM</span>: CPU and memory usage percentage - •
<span>TIME+</span>: Cumulative CPU time used by the process from startup to now (accurate to milliseconds), format is<span>hours:minutes:seconds.milliseconds</span> - •
<span>COMMAND</span>: Process name
Interactive Operations (Press the following keys within the <span>top</span> interface):
- •
<span>q</span>→ Exit - •
<span>P</span>→ Sort by CPU usage (default) - •
<span>M</span>→ Sort by memory usage - •
<span>k</span>→ Kill process (need to enter PID and signal, default 15) - •
<span>r</span>→ Adjust process priority (nice value) - •
<span>1</span>→ Show/hide usage of each CPU core - •
<span>h</span>→ Show help menu
4. Advanced Usage Methods (Essential for Advanced Users)
4.1 Customized Display
# Monitor specific user processes
top -u www-data
# Monitor MySQL process (assuming PID is 1234)
top -p 1234
# Refresh every 0.5 seconds (use with caution, high frequency may increase load)
top -d 0.5
# Display full command line (toggle by pressing 'c')
# In the top interface, press 'c', the COMMAND column will show the full path and parameters
4.2 Batch Mode + Data Collection
# Output 3 times, interval of 2 seconds, redirect to file (suitable for cron scheduled collection)
top -b -n 3 -d 2 > /tmp/top.log
# Only capture the top 5 CPU-consuming processes for alert scripts
top -b -n 1 | head -12 | tail -5
4.3 Field Customization (Press ‘f’ to enter field management)
In the <span>top</span> interface, press <span>f</span>, you can use the arrow keys and space bar to select which columns to show/hide, for example:
- • Add
<span>PPID</span>(Parent Process ID) → Track process tree - • Add
<span>TIME+</span>→ Cumulative CPU time accurate to one-hundredth of a second - • Add
<span>CODE</span>/<span>DATA</span>→ View memory in code and data segments
4.4 Save Configuration
After adjusting the display in the <span>top</span> interface (such as sorting, fields), press <span>W</span> (uppercase) to write the current configuration to <span>~/.toprc</span>, which will take effect automatically the next time you start!
5. Best Practices (Expert Experience Summary)
✅ Practice 1: Focus on “Load Average” Rather Than Instant CPU
- •
<span>load average: 1.5, 1.0, 0.5</span>indicates the system was overloaded in the past 1 minute (> number of CPU cores), but is recovering. This reflects trends better than looking at<span>%CPU</span>alone.
✅ Practice 2: Identify “Zombie Processes” and “D State Processes”
- •
<span>Z</span>(Zombie): Process has ended but the parent process has not reclaimed it → need to check the parent process or restart - •
<span>D</span>(Uninterruptible Sleep): Usually stuck in I/O (e.g., disk failure) → dangerous! May require a forced restart
✅ Practice 3: Analyze Memory by Looking at <span>avail Mem</span> Rather Than <span>free</span>
- • Linux utilizes free memory for caching (buff/cache),
<span>avail Mem</span>=<span>free</span>+<span>reclaimable cache</span>, which is the actual available memory.
✅ Practice 4: Use in Combination with <span>iotop</span> and <span>iftop</span>
- •
<span>top</span>cannot see disk and network bottlenecks → use<span>iotop</span>to check I/O, and<span>iftop</span>to check bandwidth, a combination to pinpoint issues.
✅ Practice 5: Use Caution with High Refresh Rates in Production Environments
- •
<span>-d 0.1</span>will significantly increase system overhead → monitoring scripts are recommended to use<span>-d 5</span>or longer.
6. Usage Examples in Shell Script Development
Example 1: Monitor High CPU Processes and Alert
#!/bin/bash
# monitor_high_cpu.sh
# Check every 5 minutes, if there are processes with CPU>80%, send email alert
THRESHOLD=80
LOG_FILE="/var/log/cpu_alert.log"
while true; do
# Get the highest CPU process (excluding top itself)
HIGH_CPU_PROC=$(top -b -n 1 | grep -v "top" | head -8 | tail -1)
CPU_USAGE=$(echo "$HIGH_CPU_PROC" | awk '{print $9}')
if (( $(echo "$CPU_USAGE > $THRESHOLD" | bc -l) )); then
echo "$(date): ALARM! High CPU Process: $HIGH_CPU_PROC" >> $LOG_FILE
# Here you can add email sending logic, e.g., mail -s "CPU Alert" [email protected] < $LOG_FILE
fi
sleep 300 # 5 minutes
done
Example 2: Batch Collect System Snapshots for Performance Analysis
#!/bin/bash
# system_snapshot.sh
# Collect top data every hour, keep for 7 days
SNAPSHOT_DIR="/var/log/top_snapshots"
mkdir -p $SNAPSHOT_DIR
# Collect data (batch mode, 1 refresh)
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
top -b -n 1 > "$SNAPSHOT_DIR/top_${TIMESTAMP}.log"
# Clean up snapshots older than 7 days
find $SNAPSHOT_DIR -name "top_*.log" -mtime +7 -delete
# Add to crontab: 0 * * * * /path/to/system_snapshot.sh
Example 3: Automate Killing Runaway Processes
#!/bin/bash
# kill_runaway_process.sh
# Automatically kill processes using more than 95% CPU and running for over 1 hour (e.g., python scripts)
MAX_CPU=95
MIN_TIME=3600 # 1 hour = 3600 seconds
# Get PIDs of processes containing python, CPU>95%, running time>3600 seconds
PIDS=$(top -b -n 1 | awk -v max_cpu="$MAX_CPU" -v min_time="$MIN_TIME" '
$12 ~ /python/ && $9 > max_cpu && $11+0 > min_time {print $1}
')
for PID in $PIDS; do
echo "Killing runaway process: PID=$PID"
kill -9 $PID # Force kill
echo "$(date): Killed PID $PID" >> /var/log/kill_runaway.log
done
Conclusion:
<span>top</span>may be an “ancient artifact”, but its design philosophy—real-time, simplicity, interactivity—still has no substitutes today. Mastering it means you have grasped the “first scalpel” for Linux performance diagnosis. Next time your server alarms, consider running<span>top</span>, and the problem may just be resolved!