Linux Mastery Series: Process Management and System Monitoring

  • Home
  • Linux OS
  • Linux Mastery Series: Process Management and System Monitoring
Front
Back
Right
Left
Top
Bottom
HEART
The Heart of Your System

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

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
Every process has several key attributes:
VIEWING
The Essential Commands

Viewing Processes

The `ps` command is your window into running processes:
Copy to clipboard
# 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
Using `top` and `htop`: Real-Time Monitoring
`top` provides a dynamic, real-time view of system processes:
Using `top` and `htop`: Real-Time Monitoring
`top` provides a dynamic, real-time view of system processes:
Copy to clipboard
# 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
Copy to clipboard
# 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)
As documented by Linux experts, “The top command provides a dynamic real-time view of running system…useful for monitoring system resources and identifying resource-heavy processes” .
MANAGING
Starting, Stopping, and Controlling

Managing Processes

Running Processes in Background
Copy to clipboard
# 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
Copy to clipboard
# 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
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.
PRIORITY

Process Priority and Nice Values

Linux uses “nice” values to determine process priority. Lower nice values mean higher priority.
Copy to clipboard
# 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
RESOURCE
Resource Usage

System Monitoring

CPU Monitoring
Copy to clipboard
# 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
Copy to clipboard
# 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:
Copy to clipboard
$ 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
NETWORKING

Network Monitoring

Copy to clipboard
# 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
Cron allows you to schedule recurring tasks—essential for backups, maintenance, and monitoring.
Copy to clipboard
# 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
Copy to clipboard
* * * * * command
│ │ │ │ │
│ │ │ │ └─── Day of week (0-7, Sunday = 0 or 7)
│ │ │ └───── Month (1-12)
│ │ └─────── Day of month (1-31)
│ └───────── Hour (0-23)
└─────────── Minute (0-59)
WINS

Quick Wins for Performance

Clear cache
carefully, on non-production
Copy to clipboard
sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
Adjust swappiness
reduce swap usage
Copy to clipboard
# 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
Copy to clipboard
# 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.

Donald Knuth, The Art of Computer Programming, 1974

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!
Front
Back
Right
Left
Top
Bottom
FAQ's

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