Skip to content

Linux Process Management Guide

Process management is a critical skill for Linux administration. This guide covers starting, stopping, monitoring, and controlling processes in Linux.


Overview: Process Management Concepts

What is a Process?

A process is a running instance of a program. Every process has: - PID (Process ID) - Unique identifier - PPID (Parent Process ID) - ID of parent process - UID (User ID) - Owner of the process - Priority - Process scheduling priority - State - Running, sleeping, stopped, zombie

Process States

State Symbol Description
Running R Currently executing or ready to run
Sleeping S Waiting for an event
Stopped T Stopped by job control signal
Zombie Z Terminated but not reaped by parent
Uninterruptible D Waiting for I/O, cannot be interrupted

Viewing Processes with ps

Basic ps Commands

# Show all processes
ps aux

# Show processes in tree format
ps auxf

# Show your processes
ps x

# Unix-style all processes
ps -ef

# Custom format
ps -eo pid,user,cpu,mem,command

Finding Specific Processes

# Find by name
ps aux | grep processname

# Better: use pgrep
pgrep processname

# Find with full command line
pgrep -f patternhere

# Show process tree
pstree

# Show specific user's processes
ps -u username

# Find PID by name
pidof nginx

Process Information

# Detailed info about specific PID
ps -p 1234 -o pid,user,cpu,mem,cmd

# Show all threads
ps -eLf

# Show process hierarchy
ps axjf

# Show with nice values
ps -eo pid,ni,cmd

# Show process start time
ps -eo pid,lstart,cmd

Sending Signals with kill

Common Signals

Signal Number Action Use Case
SIGHUP 1 Reload config Reload without stopping
SIGINT 2 Interrupt Ctrl+C in terminal
SIGKILL 9 Force kill Unresponsive processes
SIGTERM 15 Graceful termination Default, clean exit
SIGSTOP 19 Pause process Suspend execution
SIGCONT 18 Continue Resume paused process

Basic kill Usage

# Terminate process (SIGTERM)
kill PID

# Force kill (SIGKILL)
kill -9 PID

# Reload configuration (SIGHUP)
kill -HUP PID

# List all signals
kill -l

# Send specific signal
kill -SIGUSR1 PID

Mass Process Termination

# Kill by name (all instances)
killall processname

# Kill with specific signal
killall -9 httpd

# Kill by pattern
pkill -f pattern

# Kill user's all processes
pkill -u username

# Kill interactively
pkill -i firefox

# Kill newest instance
pkill -n processname

# Kill oldest instance
pkill -o processname

Safe Kill Procedures

# Try graceful termination first
kill PID
sleep 5

# Then force if still running
kill -9 PID

# Or in one command with timeout
timeout 10 kill PID || kill -9 PID

# Kill process group
kill -TERM -$(ps -o pgid= PID)

Process Priority with nice and renice

Understanding Priority

  • Nice values range from -20 (highest priority) to 19 (lowest priority)
  • Default nice value is 0
  • Only root can set negative nice values
  • Lower nice value = higher priority

Starting Processes with nice

# Start with nice value 10
nice -n 10 command

# Start with high priority (requires root)
sudo nice -n -10 important-process

# Start with low priority
nice -n 19 background-job

# Default nice (nice value 10)
nice command

Changing Priority with renice

# Change priority of running process
renice -n 5 -p PID

# Renice all processes of user
renice -n 10 -u username

# Renice process group
renice -n 15 -g groupid

# Make process highest priority (requires root)
sudo renice -n -20 -p PID

# Make process lowest priority
renice -n 19 -p PID

Priority Management Examples

# Start CPU-intensive task with low priority
nice -n 19 find / -name "*.log" > results.txt 2>/dev/null &

# Increase priority of important database
sudo renice -n -5 -p $(pidof mysqld)

# Lower priority of backup process
renice -n 15 -p $(pgrep backup)

Background and Foreground Jobs

Job Control Basics

# Start process in background
command &

# Send running process to background
# Press Ctrl+Z to suspend
bg

# Bring background job to foreground
fg

# List jobs
jobs

# Show jobs with PIDs
jobs -l

Managing Background Jobs

# Start in background
long-running-command &

# List all jobs
jobs
# Example output:
# [1]   Running                 long-running-command &
# [2]-  Stopped                 vim file.txt
# [3]+  Running                 python script.py &

# Bring job 2 to foreground
fg %2

# Send job 1 to background
bg %1

# Kill job 3
kill %3

Advanced Job Control

# Suspend current foreground job
# Press Ctrl+Z

# Resume in background
bg %1

# Resume in foreground
fg %1

# Disown job (continue after logout)
disown %1

# Start detached from terminal
nohup command &

# Check disowned jobs
jobs -l

Process Monitoring and Management

Real-Time Process Viewing

# Interactive process viewer
top

# Enhanced process viewer
htop

# Watch specific process
watch -n 1 'ps aux | grep processname'

# Monitor resource usage
pidstat 1

# Detailed process info
cat /proc/PID/status
cat /proc/PID/cmdline

Process Resource Limits

# View current limits
ulimit -a

# Set max processes
ulimit -u 1000

# Set max open files
ulimit -n 4096

# Set max memory
ulimit -m 1048576

# View process limits
cat /proc/PID/limits

System Service Management with systemd

Basic systemctl Commands

# Start service
sudo systemctl start servicename

# Stop service
sudo systemctl stop servicename

# Restart service
sudo systemctl restart servicename

# Reload configuration
sudo systemctl reload servicename

# Enable service at boot
sudo systemctl enable servicename

# Disable service at boot
sudo systemctl disable servicename

# Check service status
systemctl status servicename

Service Information

# List all services
systemctl list-units --type=service

# List running services
systemctl list-units --type=service --state=running

# List failed services
systemctl --failed

# Show service dependencies
systemctl list-dependencies servicename

# Check if service is enabled
systemctl is-enabled servicename

# Check if service is active
systemctl is-active servicename

Service Logs with journalctl

# View service logs
journalctl -u servicename

# Follow logs in real-time
journalctl -u servicename -f

# Show recent logs
journalctl -u servicename -n 50

# Logs since yesterday
journalctl -u servicename --since yesterday

# Logs between dates
journalctl -u servicename --since "2024-01-01" --until "2024-01-31"

# Show kernel messages
journalctl -k

Daemonizing Processes

Using nohup

# Run command immune to hangups
nohup long-running-command &

# Redirect output
nohup command > output.log 2>&1 &

# Silent background process
nohup command > /dev/null 2>&1 &

Using screen

# Start new screen session
screen -S sessionname

# Detach from screen
# Press Ctrl+A then D

# List screens
screen -ls

# Reattach to screen
screen -r sessionname

# Kill screen session
screen -X -S sessionname quit

Using tmux

# Start new tmux session
tmux new -s sessionname

# Detach from tmux
# Press Ctrl+B then D

# List sessions
tmux ls

# Attach to session
tmux attach -t sessionname

# Kill session
tmux kill-session -t sessionname

Process Monitoring Scripts

CPU Usage Monitor

#!/bin/bash
# Monitor top CPU processes
while true; do
    clear
    date
    echo "Top 5 CPU processes:"
    ps aux --sort=-%cpu | head -6
    sleep 5
done

Memory Monitor

#!/bin/bash
# Monitor top memory processes
while true; do
    clear
    date
    echo "Top 5 Memory processes:"
    ps aux --sort=-%mem | head -6
    sleep 5
done

Process Watchdog

#!/bin/bash
# Restart process if it dies
PROCESS="important-service"

while true; do
    if ! pgrep -x "$PROCESS" > /dev/null; then
        echo "$(date): $PROCESS is not running. Starting..."
        systemctl start $PROCESS
    fi
    sleep 30
done

Troubleshooting Process Issues

High CPU Usage

# Find high CPU processes
ps aux --sort=-%cpu | head -10

# Monitor specific process
top -p PID

# Trace system calls
strace -p PID

# Profile CPU usage
perf top -p PID

Zombie Processes

# Find zombie processes
ps aux | grep 'Z'

# Find parent of zombie
ps -o ppid= -p ZOMBIE_PID

# Kill parent to reap zombie
kill PARENT_PID

# Prevent zombies with proper signal handling

Unresponsive Processes

# Check process state
ps aux | grep processname

# Try graceful termination
kill PID

# Wait and check
sleep 5
ps -p PID

# Force kill if necessary
kill -9 PID

# Check for file locks
lsof -p PID

Too Many Processes

# Count processes by user
ps aux | awk '{print $1}' | sort | uniq -c | sort -rn

# Find process creating children
ps axjf

# Limit user processes
ulimit -u 100

# Kill all user processes
pkill -u username

Best Practices

Process Management

  1. Use graceful shutdown first - kill PID before kill -9 PID
  2. Monitor resource usage - Regular checks with top/htop
  3. Set appropriate priorities - Use nice for background tasks
  4. Use systemd for services - Better than manual process management
  5. Clean up zombies - Ensure proper parent process handling

Security Considerations

# List processes by all users
sudo ps aux

# Find processes running as root
ps -U root -u root

# Check for suspicious processes
ps aux | grep -v "^\[" | sort -k3 -rn | head -10

# Monitor new processes
watch -n 1 'ps aux --sort=-start_time | head -10'

Quick Reference

Essential Commands

# View processes
ps aux                 # All processes
pgrep name            # Find by name
pidof name            # Get PID

# Control processes
kill PID              # Terminate
kill -9 PID           # Force kill
killall name          # Kill all by name
pkill pattern         # Kill by pattern

# Job control
command &             # Background
Ctrl+Z                # Suspend
bg                    # Resume in background
fg                    # Bring to foreground
jobs                  # List jobs

# Priority
nice -n 10 cmd        # Start with nice
renice -n 5 -p PID    # Change priority

# Services
systemctl start name  # Start service
systemctl stop name   # Stop service
systemctl status name # Check status

# Monitoring
top                   # Process monitor
htop                  # Enhanced monitor
ps aux --sort=-%cpu   # Top CPU users