Understanding Linux Processes
Every program you run on Linux is a process. Understanding process management is like understanding the nervous system of your computer—it’s fundamental to becoming an effective developer and system administrator. As the Linux Kernel documentation states, “kernel – process management code (including support for kernel thread, workqueues), scheduler, tracing, time management, generic irq code, locking” (linux-kernel-labs.github.io/refs/heads/master/lectures/intro.html).
In this next part of our Linux Mastery series, we’ll explore how to monitor, control, and optimize processes—skills that separate junior developers from senior engineers.
What Is a Process?
A process is simply an instance of a running program. When you execute a command, the kernel creates a process with a unique Process ID (PID). According to Linux documentation, the kernel’s process management handles “scheduling, tracing, time management” among other critical functions.
Process Attributes
- PID (Process ID): Unique identifier
- PPID (Parent Process ID): The process that spawned this one
- User: Who owns the process
- State: Running, sleeping, stopped, or zombie
- Priority: CPU scheduling priority
- Memory usage: RAM consumed by the process
Viewing Processes
# View your processes
ps
# View all processes with detailed information
ps aux
# View in hierarchical tree format
ps auxf
# View processes for specific user
ps -u username
# View process by PID
ps -p 1234
# Custom format output
ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head -10
# View threads
ps -eLf
# Output explanation:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.4 168976 11872 ? Ss Jan27 0:02 /sbin/init
- USER: Process owner
- PID: Process ID
- %CPU: CPU usage percentage
- %MEM: Memory usage percentage
- VSZ: Virtual memory size
- RSS: Resident set size (physical memory)
- STAT: Process state (R=running, S=sleeping, D=uninterruptible, Z=zombie, T=stopped)
Using `top` and `htop`: Real-Time Monitoring
Using `top` and `htop`: Real-Time Monitoring
# Launch top
top
# Sort by memory usage (press M)
# Sort by CPU usage (press P)
# Kill process (press k, then enter PID)
# Filter by user (press u, then username)
# Quit (press q)
# Run top in batch mode (useful for scripts)
top -b -n 1 > system-snapshot.txt
# Monitor specific user
top -u username
# Update every 2 seconds
top -d 2
Enhanced alternative - htop
# install with `sudo apt install htop
# Launch htop (more user-friendly than top)
htop
# Features:
# - Mouse support
# - Color coding
# - Tree view (F5)
# - Search (F3)
# - Kill process (F9)
# - Nice/Renice (F7/F8)
Managing Processes
Running Processes in Background
# Run command in background (append &)
./long-running-script.sh &
# View background jobs
jobs
# Bring job to foreground
fg %1
# Send current job to background (Ctrl+Z, then bg)
# Press Ctrl+Z to suspend
bg
# Run process immune to hangup signal
nohup ./script.sh &
# Run process and redirect output
nohup python3 server.py > output.log 2>&1 &
Killing Processes
# Graceful termination (SIGTERM)
kill PID
# Force kill (SIGKILL)
kill -9 PID
# Kill by process name
pkill process-name
# Kill all instances
killall firefox
# Kill processes by user
pkill -u username
# Kill with specific signal
kill -SIGTERM PID
kill -15 PID # Same as SIGTERM
# View all signals
kill -l
Common Signals
- SIGTERM (15): Graceful termination (default)
- SIGKILL (9): Force kill (use as last resort)
- SIGHUP (1): Hang up (reload configuration)
- SIGINT (2): Interrupt (Ctrl+C)
- SIGSTOP (19): Pause process
Best Practice:
Always try `kill` (SIGTERM) before `kill -9` (SIGKILL). SIGTERM allows processes to clean up, close files, and exit gracefully. SIGKILL is immediate and doesn't allow cleanup.
Process Priority and Nice Values
# View process priorities
ps -eo pid,ni,comm
# Start process with specific nice value (-20 to 19)
nice -n 10 ./cpu-intensive-task.sh
# Change nice value of running process
renice -n 5 -p PID
# Run with highest priority (requires root)
sudo nice -n -20 ./critical-task.sh
# Run with lowest priority
nice -n 19 ./background-backup.sh
System Monitoring
CPU Monitoring
# CPU information
lscpu
# CPU usage by core
mpstat -P ALL 1
# Real-time CPU monitoring
watch -n 1 'cat /proc/loadavg'
# Load average
uptime
# CPU-intensive processes
ps aux --sort=-%cpu | head -10
Memory Monitoring
# Memory usage summary
free -h
# Detailed memory information
cat /proc/meminfo
# Memory-intensive processes
ps aux --sort=-%mem | head -10
# Watch memory in real-time
watch -n 1 free -h
# Per-process memory breakdown
pmap PID
# System-wide memory map
vmstat 1
Memory Output Explained:
$ free -h
total used free shared buff/cache available
Mem: 15Gi 8.2Gi 1.1Gi 412Mi 6.2Gi 6.5Gi
Swap: 2.0Gi 256Mi 1.7Gi
- total: Total physical RAM
- used: RAM used by processes
- free: Completely unused RAM
- buff/cache: Used by kernel for caching (can be freed if needed)
- available: RAM available for new processes
Network Monitoring
# Network interface statistics
ifconfig
ip addr show
# Network connections
netstat -tulpn # All listening ports
ss -tulpn # Modern replacement for netstat
# Real-time network traffic
iftop # Install: sudo apt install iftop
# Monitor specific port
netstat -an | grep :80
# Active connections
ss -s
# Bandwidth usage per process
nethogs # Install: sudo apt install nethogs
# DNS lookup
nslookup example.com
dig example.com
# Trace network route
traceroute google.com
# Test connectivity
ping -c 4 8.8.8.8
# Download speed test
wget -O /dev/null http://speedtest.tele2.net/100MB.zip
Cron Jobs: Automating Tasks
# Edit cron table
crontab -e
# List current cron jobs
crontab -l
# Remove all cron jobs
crontab -r
# Edit cron for specific user (root)
sudo crontab -u username -e
Cron Syntax
* * * * * command
│ │ │ │ │
│ │ │ │ └─── Day of week (0-7, Sunday = 0 or 7)
│ │ │ └───── Month (1-12)
│ │ └─────── Day of month (1-31)
│ └───────── Hour (0-23)
└─────────── Minute (0-59)
Quick Wins for Performance
Clear cache
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
Adjust swappiness
# View current value
cat /proc/sys/vm/swappiness
# Reduce (persists after reboot when added to sysctl.conf)
sudo sysctl vm.swappiness=10
Kill zombie processes
# Find zombies
ps aux | grep 'Z'
# Kill parent process (zombies can't be killed directly)
kill -9 PPID
Premature optimization is the root of all evil.
Thank You for Spending Your Valuable Time
I truly appreciate you taking the time to read blog. Your valuable time means a lot to me, and I hope you found the content insightful and engaging!
Frequently Asked Questions
First, try accessing the system via SSH from another machine. Use `top` or `htop` to identify the culprit process. Check the process legitimacy before killing it. For critical production systems, consider implementing CPU cgroups to limit resource usage per service. As documented by Linux kernel developers, the scheduler manages CPU allocation, but user intervention may be necessary for runaway processes.
Use `watch` to monitor process status: `watch -n 1 'ps aux | grep process-name'`. Check system logs with `journalctl -u service-name -f` for services, or application logs for details. Implement automatic restart using systemd service configuration with `Restart=always`. Consider using monitoring tools like Nagios or Prometheus for production environments.
Linux uses swap proactively to optimize performance, moving inactive memory pages to swap to make room for disk cache. This is controlled by the `swappiness` parameter (default 60). If this behavior is undesirable, reduce swappiness: `sudo sysctl vm.swappiness=10`. However, some swap usage is normal and healthy—only worry if swap usage is consistently high while RAM is exhausted.
Use `iotop` (with sudo) to see real-time disk I/O per process: `sudo iotop -o` (shows only active processes). For historical data, check `/proc/[PID]/io` for specific processes. You can also use `lsof` to see which files processes have open. According to Linux documentation, the kernel tracks all I/O operations, making this information accessible through the /proc filesystem.
Always implement these practices: (1) Use flock to prevent overlapping executions, (2) Log all output with timestamps, (3) Set up email alerts for failures, (4) Use absolute paths for all commands and files, (5) Test scripts manually before scheduling, (6) Implement timeout mechanisms using `timeout` command, (7) Document all cron jobs in version control. For critical tasks, consider using systemd timers instead, which offer better logging and service integration.
Comments are closed