Your server is slow. CPU is at 100%. Which process is causing the problem? How do you stop it? How do you run a long task without keeping your terminal open? Process management answers these questions. Every DevOps engineer needs to identify, monitor, and control processes. In this lesson, you'll learn the tools that give you X-ray vision into your running system.
1. Learning Objectives
By the end of this lesson, you will be able to:
- View processes with
ps,top, andhtop - Understand process states (R, S, D, Z, T)
- Send signals to processes with
killandkillall - Run processes in background (
&) - Use job control (
jobs,fg,bg) - Keep processes running after logout (
nohup,disown,screen,tmux)
2. Why This Matters
Real-world scenario: A runaway process is consuming 100% CPU. Your monitoring alert is firing. You SSH into the server and need to:
- Find which process is causing the problem
- Stop it immediately (without rebooting)
- Identify what triggered it to prevent recurrence
Without process management skills, you're helpless. With them, you fix it in 30 seconds.
3. Core Concepts
What is a Process?
A process is a running instance of a program. Every command you run creates a process with a unique Process ID (PID).
- PID: Unique identifier for each process
- PPID: Parent Process ID (who started it)
- UID: User ID that owns the process
- nice value: Priority (-20 to 19, lower = higher priority)
Viewing Processes with ps
# Basic ps (only current shell processes)
ps
# All processes
ps aux # BSD syntax (most common)
ps -ef # System V syntax
# Common ps options explained
ps aux --sort=-%cpu # Sort by CPU usage (highest first)
ps aux --sort=-%mem # Sort by memory usage
ps -u username # Processes for specific user
ps -C process_name # Processes with specific command
ps -p 1234 # Specific PID
# Custom output format
ps -eo pid,ppid,user,%cpu,%mem,etime,cmd --sort=-%cpu | head -20
$ ps aux | head -5
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.1 168000 12000 ? Ss Jan17 0:02 /sbin/init
root 123 0.5 0.2 45000 8000 ? S Jan17 5:30 /usr/bin/nginx
www-data 456 0.1 0.1 46000 7500 ? S Jan17 1:20 nginx: worker
ubuntu 7890 2.3 5.2 800000 500000 ? Sl Jan17 45:12 /usr/bin/python3 app.py
Process States
Real-time Monitoring with top and htop
# Top commands
# ------------
top # Start top
# Inside top:
# h - help
# q - quit
# P - sort by CPU
# M - sort by Memory
# k - kill process (prompts for PID)
# r - renice (change priority)
# u - show only specific user
# 1 - show each CPU core individually
# c - show full command line
# Batch mode (for scripts)
top -b -n 1 | head -20
# htop (better alternative, install first)
# sudo apt install htop
htop
# Inside htop:
# F2 - setup/configuration
# F3 - search
# F5 - tree view
# F6 - sort by column
# F9 - kill process
# F10 - quit
Killing Processes (Signals)
# Kill signals (most common)
# 1 (SIGHUP) - Hang up (reload config)
# 2 (SIGINT) - Interrupt (Ctrl+C)
# 9 (SIGKILL) - Kill (force, cannot be ignored)
# 15 (SIGTERM) - Terminate (graceful, default)
# 18 (SIGCONT) - Continue (resume stopped process)
# 19 (SIGSTOP) - Stop (pause process)
# Send signals
kill PID # SIGTERM (graceful kill)
kill -9 PID # SIGKILL (force kill)
kill -15 PID # Same as default
kill -1 PID # SIGHUP (reload config)
kill -STOP PID # Pause process
kill -CONT PID # Resume process
# Kill by name
pkill process_name # Kill by name
pkill -9 process_name # Force kill by name
killall process_name # Kill all instances
# Example: Reload nginx configuration
sudo kill -1 $(cat /var/run/nginx.pid)
# or
sudo systemctl reload nginx
Job Control (Foreground/Background)
# Run command in background
long_running_command &
# View background jobs
jobs
# Output: [1] Running long_running_command &
# Bring background job to foreground
fg %1
# Suspend foreground job (Ctrl+Z) then background it
# 1. Run command
sleep 100
# 2. Press Ctrl+Z
# 3. Put in background
bg
# Start multiple background commands
command1 & command2 & command3 &
jobs
# Kill specific background job
kill %1
Keeping Processes Alive After Logout
# Method 1: nohup (no hang up)
nohup long_running_command &
# Output goes to nohup.out
nohup python script.py > output.log 2>&1 &
# Method 2: disown
long_running_command &
disown %1 # Remove from shell's job table
# Method 3: screen (best for long sessions)
screen -S my_session
# Run commands inside screen
# Detach: Ctrl+A, then D
screen -ls # List sessions
screen -r my_session # Reattach
# Method 4: tmux (modern alternative)
tmux new -s my_session
tmux detach # Ctrl+B, D
tmux ls
tmux attach -t my_session
4. Hands-on Practice Lab
# Create a test script
cat > ~/test_process.sh << 'EOF'
#!/bin/bash
echo "Process started with PID: $$"
while true; do
echo "Running... $(date)"
sleep 5
done
EOF
chmod +x ~/test_process.sh
Exercise 1: Process Exploration
# Start test process in background
~/test_process.sh &
# Find its PID
ps aux | grep test_process
# Check its state and resource usage
top -p $PID
# View process tree
pstree -p $PPID
# Check open files
lsof -p $PID
# Check process environment
cat /proc/$PID/environ | tr '\0' '\n'
Exercise 2: CPU Stress Test and Kill
# Create CPU stress test
yes > /dev/null &
# Monitor CPU usage
htop
# or
top -bn1 | grep -E "%Cpu|yes"
# Kill the stress process
pkill yes
# or
kill -9 $(pgrep yes)
5. Complete Project: System Monitor Script
#!/bin/bash
# system_monitor.sh - Monitor system processes and alert on issues
# Configuration
CPU_THRESHOLD=90
MEM_THRESHOLD=90
ALERT_EMAIL="admin@example.com"
LOG_FILE="/var/log/system_monitor.log"
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
echo "=== System Monitor Started at $(date) ==="
# Function: Find top CPU processes
top_cpu() {
echo -e "\n${YELLOW}Top 5 CPU-consuming processes:${NC}"
ps aux --sort=-%cpu | head -6 | tail -5
}
# Function: Find top memory processes
top_memory() {
echo -e "\n${YELLOW}Top 5 Memory-consuming processes:${NC}"
ps aux --sort=-%mem | head -6 | tail -5
}
# Function: Check for zombie processes
check_zombies() {
zombies=$(ps aux | awk '$8=="Z"' | wc -l)
if [ "$zombies" -gt 0 ]; then
echo -e "${RED}⚠️ Warning: $zombies zombie processes found!${NC}"
ps aux | awk '$8=="Z"'
fi
}
# Function: Check high CPU usage
check_high_cpu() {
high_cpu=$(ps aux | awk -v threshold="$CPU_THRESHOLD" '$3 > threshold {print " PID:" $2 " CPU:" $3 "% CMD:" $11}')
if [ -n "$high_cpu" ]; then
echo -e "${RED}⚠️ High CPU usage detected:${NC}"
echo "$high_cpu"
fi
}
# Function: Check high memory usage
check_high_memory() {
high_mem=$(ps aux | awk -v threshold="$MEM_THRESHOLD" '$4 > threshold {print " PID:" $2 " MEM:" $4 "% CMD:" $11}')
if [ -n "$high_mem" ]; then
echo -e "${RED}⚠️ High Memory usage detected:${NC}"
echo "$high_mem"
fi
}
# Function: Check system load
check_load() {
load=$(uptime | awk -F'load average:' '{print $2}')
cores=$(nproc)
echo -e "${YELLOW}System Load:${NC} $load (Cores: $cores)"
}
# Main execution
top_cpu
top_memory
check_load
check_zombies
check_high_cpu
check_high_memory
echo -e "\n${GREEN}=== Monitor completed ===${NC}"
# Log results
{
echo "[$(date)] System Monitor Report"
top_cpu
top_memory
check_load
} >> "$LOG_FILE"
echo "Log saved to $LOG_FILE"
6. Common Errors & Solutions
7. Summary Checklist
8. Practice Exercise
Challenge: Your server is running slow. Write a command that:
- Finds the top 3 CPU-consuming processes
- Shows their PIDs, CPU percentage, and command name
- Saves this information to a file called
cpu_report.txt - If any process is using over 90% CPU, send a warning to the terminal
9. Next Steps
Next lesson: Linux Lesson 1.5: Text Processing with grep, sed, awk
You'll learn to:
- Search files with
grepand patterns - Transform text with
sed - Process structured data with
awk - Parse logs and extract information
Comments (0)
This is exactly what I needed! The initContainer approach solved our migration issues completely. Thanks for the detailed guide!
ReplyLeave a Comment