Process Monitoring (ps, top, htop, nice, renice)

Effective process monitoring is crucial for maintaining system performance, identifying resource bottlenecks, and optimizing process execution. Understanding how to monitor, analyze, and control process priorities enables you to keep your Linux systems running smoothly under varying workloads. This comprehensive guide covers essential monitoring tools and priority management techniques.

Process Monitoring Tools Comparison

Tool Type Interface Real-time Best For
ps Snapshot Command-line No Process details, scripting
top Interactive Text-based UI Yes System overview, quick monitoring
htop Interactive Enhanced text UI Yes Detailed monitoring, process control
nice Priority Command-line N/A Setting initial priority
renice Priority Command-line N/A Adjusting running process priority
Quick Reference:
ps - Take process snapshot, detailed information
top - Real-time system monitoring, basic interface
htop - Enhanced top with colors and mouse support
nice - Start process with specific priority
renice - Change priority of running process
• Priority range: -20 (highest) to 19 (lowest)

Process Monitoring Workflow

Complete Process Management Cycle

System Check
Identify Issues
Analyze Processes
Adjust Priority
Monitor Results

Essential Process Monitoring Commands

📊
ps

Display information about active processes - process status.

ps [options]

Common Usage:

  • ps aux - All processes with details
  • ps -ef - Full format listing
  • ps -u username - User's processes
  • ps -p PID - Specific process
  • ps --forest - Process tree

Key Output Fields:

  • PID - Process ID
  • USER - Process owner
  • %CPU - CPU usage
  • %MEM - Memory usage
  • COMMAND - Command line
📈
top

Display Linux tasks in real-time, interactive system monitor.

top [options]

Interactive Commands:

  • P - Sort by CPU usage
  • M - Sort by memory usage
  • k - Kill process
  • r - Renice process
  • q - Quit
  • h - Help

Header Information:

  • System uptime and load average
  • Total tasks and their states
  • CPU usage statistics
  • Memory and swap usage
🎨
htop

Interactive process viewer with enhanced features and colors.

htop [options]

Enhanced Features:

  • Colorful display
  • Mouse support
  • Vertical and horizontal scrolling
  • Tree view of processes
  • Easy process management

Interactive Controls:

  • F9 - Kill process
  • F7/F8 - Renice (decrease/increase)
  • F6 - Sort by column
  • F5 - Tree view
  • F4 - Filter processes

Process Priority Management

Nice Value Priority Level CPU Access Use Case Default For
-20 to -1 High Priority More frequent Critical system tasks System processes
0 Normal Priority Standard Regular user processes User processes (default)
1 to 19 Low Priority Less frequent Background tasks, batch jobs Non-critical processes
nice

Run a program with modified scheduling priority.

nice [OPTION] [COMMAND [ARG]...]

Usage:

  • nice -n 5 command - Run with nice +5
  • nice -n -10 command - Run with high priority
  • nice command - Run with default nice +10

Examples:

  • nice -n 15 ./backup.sh - Low priority backup
  • nice -n -5 ./video_encode.sh - High priority encoding
  • nice -n 19 find / -name "*.log" - Low priority search
🔄
renice

Alter priority of running processes.

renice [-n] priority [[-p] pid ...] [[-g] pgrp ...] [[-u] user ...]

Usage:

  • renice -n 5 -p 1234 - Set PID 1234 to nice 5
  • renice -n -5 -u username - Set user's processes
  • renice -n 10 -g 5678 - Set process group

Examples:

  • renice -n 15 1234 - Make process low priority
  • renice -n -5 -p 5678 9012 - Multiple PIDs
  • renice -n 10 -u developer - All user's processes
👑

Privilege Requirements

Understanding permission needs for priority changes.

sudo required for certain operations

Permission Rules:

  • Any user can lower priority (increase nice)
  • Only root can increase priority (decrease nice)
  • Users can renice their own processes
  • Root can renice any process

Examples:

  • nice -n 10 command - Any user OK
  • nice -n -5 command - Requires sudo
  • renice -n -5 -p 1234 - Requires sudo

Advanced Process Monitoring

🔍

Process Filtering & Search

Techniques for finding specific processes.

pgrep | pstree | ps grep

Search Methods:

  • pgrep process_name - Find PIDs by name
  • ps aux | grep pattern - Search process list
  • pstree - Display process tree
  • ps -C command_name - Processes by command

Examples:

  • pgrep nginx
  • ps aux | grep java
  • pstree -p - With PIDs
📋

Custom ps Output Formats

Create tailored process listings.

ps -o field1,field2,...

Common Fields:

  • pid - Process ID
  • user - User name
  • pcpu - CPU percentage
  • pmem - Memory percentage
  • vsz - Virtual memory size
  • rss - Resident set size
  • start - Start time
  • time - CPU time

Example:

ps -eo pid,user,pcpu,pmem,comm --sort=-pcpu | head -10
🖥️

System Resource Monitoring

Additional tools for comprehensive monitoring.

vmstat | iostat | mpstat

System Tools:

  • vmstat 1 - Virtual memory statistics
  • iostat 1 - I/O statistics
  • mpstat 1 - CPU statistics
  • free -h - Memory usage
  • df -h - Disk space

Examples:

  • vmstat 1 5 - 5 reports at 1-second intervals
  • iostat -dx 1 - Extended disk stats

Practical Monitoring Examples

Real-World Process Monitoring Scenarios

# 1. Basic Process Monitoring
# View all processes
ps aux

# View specific user processes
ps -u username

# Find process by name
pgrep nginx
ps aux | grep nginx

# 2. Real-time Monitoring with top
# Start top with specific update delay
top -d 1

# Save top configuration for future use
# Press 'W' (capital w) to write configuration

# Monitor specific user only
top -u username

# 3. Advanced htop Usage
# Start htop with tree view
htop -t

# Show custom meters
# Press F2 → Meters to customize display

# 4. Priority Management Examples
# Start process with low priority
nice -n 15 ./data_processing.sh

# Start process with high priority (requires sudo)
sudo nice -n -10 ./critical_task.sh

# Change priority of running process
renice -n 5 1234

# Change priority for all user processes
renice -n 10 -u developer

# 5. Process Analysis and Troubleshooting
# Find top CPU consuming processes
ps -eo pid,user,ppid,pcpu,pmem,comm --sort=-pcpu | head -10

# Find top memory consuming processes
ps -eo pid,user,ppid,pcpu,pmem,comm --sort=-pmem | head -10

# Monitor process tree
pstree -p
pstree -p username

# 6. Continuous Monitoring
# Monitor with watch command
watch -n 1 'ps -eo pid,user,pcpu,pmem,comm --sort=-pcpu | head -10'

# Log process statistics
while true; do
    echo "$(date): $(ps -eo pcpu,pmem --no-headers | awk '{cpu+=$1; mem+=$2} END {print "CPU: " cpu "% MEM: " mem "%"}')" >> process_stats.log
    sleep 5
done

# 7. Batch Process Management
# Start multiple processes with different priorities
nice -n 10 ./batch_job1.sh &
nice -n 15 ./batch_job2.sh &
nice -n 5 ./batch_job3.sh &

# Monitor their progress
watch -n 2 'ps -eo pid,ni,pcpu,pmem,comm | grep batch_job'

# 8. System Health Check Script
#!/bin/bash
echo "=== System Health Check ==="
echo "Load Average: $(cat /proc/loadavg)"
echo "Memory Usage:"
free -h
echo "Top 5 CPU Processes:"
ps -eo pid,user,pcpu,pmem,comm --sort=-pcpu | head -6
echo "Top 5 Memory Processes:"
ps -eo pid,user,pcpu,pmem,comm --sort=-pmem | head -6

# 9. Process Priority Optimization
# Identify CPU-intensive processes that could be lower priority
ps -eo pid,user,ni,pcpu,comm --sort=-pcpu | head -10

# Identify important processes that need higher priority
ps -eo pid,user,ni,pcpu,comm --sort=-pcpu | grep -E "(nginx|mysql|redis)"

# 10. Automated Priority Adjustment
# Script to lower priority of batch processes at system load
#!/bin/bash
LOAD=$(cat /proc/loadavg | cut -d' ' -f1 | cut -d'.' -f1)
if [ $LOAD -gt 5 ]; then
    echo "High load detected, adjusting priorities..."
    # Find batch processes and lower their priority
    pgrep -f "batch_process" | while read pid; do
        current_nice=$(ps -o ni -p $pid --no-headers)
        if [ $current_nice -lt 10 ]; then
            renice -n 10 $pid
            echo "Adjusted priority for PID $pid"
        fi
    done
fi

Common Use Cases

System Administration

  • Performance Monitoring: top, htop for real-time system health
  • Capacity Planning: ps with custom formats for trend analysis
  • Troubleshooting: Identify resource hogs with ps aux --sort=-%cpu

Development & Testing

  • Application Profiling: Monitor resource usage during testing
  • Load Testing: Use nice to prioritize test framework over test applications
  • Debugging: Track process behavior and resource consumption

Production Operations

  • Service Monitoring: Continuous monitoring of critical services
  • Priority Management: Ensure critical services get adequate resources
  • Batch Processing: Use low priority for non-critical batch jobs

Advanced Monitoring Techniques

📊

Process Accounting

Track process activity and resource usage.

psacct | acct

Features:

  • Track all process executions
  • Monitor CPU time used
  • Track commands run by users
  • Historical process data

Commands:

  • lastcomm - Show last commands executed
  • sa - Summary of process accounting
  • ac - Connect time accounting
🔔

Automated Alerts

Set up monitoring with automatic notifications.

Custom scripts | Monitoring tools

Alert Scenarios:

  • High CPU usage by specific process
  • Memory exhaustion alerts
  • Process crash detection
  • Priority violation alerts

Example Script:

#!/bin/bash
CPU_THRESHOLD=90
ps -eo pid,pcpu,comm --sort=-pcpu | head -10 | while read pid cpu comm; do
    if [[ $cpu > $CPU_THRESHOLD ]]; then
        echo "ALERT: High CPU usage: $comm (PID: $pid) - $cpu%"
        # Send notification
    fi
done
📈

Performance Baselines

Establish normal performance metrics.

Historical data collection

Baseline Metrics:

  • Normal CPU usage patterns
  • Typical memory consumption
  • Process count trends
  • Load average patterns

Implementation:

  • Regular ps snapshots
  • top batch mode output
  • Custom monitoring scripts
  • Log analysis tools
Important Considerations:
• Setting very high priorities (-20) can starve other processes
• Regular users cannot increase priority (decrease nice value)
kill -STOP and kill -CONT can manage process execution
• Zombie processes need parent process termination to be cleared
• High system load might require process termination, not just priority adjustment
• Always monitor system-wide impact when changing priorities
Pro Tips:
• Use htop for interactive process management
• Combine watch with ps for continuous monitoring
• Set up aliases for common monitoring commands
• Use --forest option to understand process hierarchies
• Monitor both CPU and memory to identify different types of bottlenecks
• Consider using atop for advanced process accounting
• Create custom ps formats for specific monitoring needs

Key Takeaways

Effective process monitoring is the foundation of system performance management and troubleshooting. By mastering tools like ps for detailed snapshots, top and htop for real-time monitoring, and nice/renice for priority control, you gain complete visibility and control over system resources. Understanding normal system behavior through baselines enables you to quickly identify anomalies and performance issues. Remember that proper priority management not only resolves immediate performance problems but also helps prevent them by ensuring critical processes receive adequate resources while non-essential tasks don't impact system responsiveness.

Next Step: Explore system logging and audit trails to complement process monitoring with comprehensive system activity tracking and security monitoring capabilities.