Quick Guide to Linux Process Management and Job Control

Effective process management is a fundamental skill for Linux users and administrators. Understanding how to monitor, control, and manipulate processes enables efficient system resource management and troubleshooting. This guide provides a practical overview of Linux process management, covering essential commands and techniques for everyday use.

Understanding Processes

What is a Process?

A process is an instance of a running program. Every command you execute creates at least one process. Processes have:

  • Process ID (PID): Unique identifier
  • Parent Process ID (PPID): ID of the process that started it
  • User ID (UID): Owner of the process
  • State: Running, sleeping, stopped, zombie
  • Priority: Scheduling priority (nice value)
  • Resources: Memory, CPU, open files

Process States

  • Running (R): Currently executing or ready to run
  • Sleeping (S): Waiting for an event (interruptible)
  • Uninterruptible Sleep (D): Waiting for I/O (cannot be interrupted)
  • Stopped (T): Suspended by signal
  • Zombie (Z): Terminated but not reaped by parent

Viewing Processes

Basic Process Listing

ps command:

# Current terminal processes
ps

## All processes (full format)
ps -ef

## All processes (BSD style)
ps aux

## Process tree
ps auxf
## or
pstree

## Specific user's processes
ps -u username

## Specific process by name
ps aux | grep nginx

Key ps output columns:

  • PID: Process ID
  • PPID: Parent Process ID
  • USER: Process owner
  • %CPU: CPU usage percentage
  • %MEM: Memory usage percentage
  • VSZ: Virtual memory size
  • RSS: Resident set size (physical memory)
  • TTY: Terminal
  • STAT: Process state
  • TIME: CPU time consumed
  • COMMAND: Command that started the process

Interactive Process Monitoring

top command:

## Launch top
top

## While in top:
## q - quit
## k - kill process
## r - renice process
## P - sort by CPU
## M - sort by memory
## u - filter by user
## h - help

htop (enhanced top):

## Install htop
sudo apt install htop  # Debian/Ubuntu
sudo dnf install htop  # Fedora
sudo pacman -S htop    # Arch

## Launch htop
htop

## Features:
## - Color-coded display
## - Mouse support
## - Tree view
## - Easy process management

atop (advanced monitoring):

## Install atop
sudo apt install atop

## Launch atop
atop

## Useful keys:
## m - memory details
## d - disk activity
## n - network activity
## c - command details

Managing Process Execution

Running Commands in Background

Ampersand (&):

## Run in background
command &

## Example
sleep 60 &

## List background jobs
jobs

nohup (no hangup):

Prevents process from terminating when terminal closes:

## Run command with nohup
nohup command &

## Output redirected to nohup.out
nohup ./long-running-script.sh &

## Redirect output
nohup ./script.sh > output.log 2>&1 &

Job Control

Suspending and resuming:

## Suspend foreground process
Ctrl+Z

## Resume in foreground
fg

## Resume in background
bg

## List jobs
jobs

## Resume specific job
fg %1    # foreground job 1
bg %2    # background job 2

Example workflow:

## Start process
./long-task

## Suspend it
Ctrl+Z
## Output: [1]+ Stopped    ./long-task

## Continue in background
bg
## Output: [1]+ ./long-task &

## Check jobs
jobs
## Output: [1]+ Running    ./long-task &

## Bring back to foreground
fg

Disowning Processes

Remove job from shell’s job list:

## Start background job
sleep 300 &

## Disown it
disown

## Shell can close without affecting process

Terminating Processes

kill Command

Send signals to processes:

## Terminate process (SIGTERM)
kill PID

## Force kill (SIGKILL)
kill -9 PID
## or
kill -KILL PID

## Graceful shutdown (SIGTERM)
kill -15 PID
## or
kill -TERM PID

## Reload configuration (SIGHUP)
kill -HUP PID

## Stop process (SIGSTOP)
kill -STOP PID

## Continue process (SIGCONT)
kill -CONT PID

Common signals:

  • SIGHUP (1): Hangup, reload configuration
  • SIGINT (2): Interrupt (Ctrl+C)
  • SIGQUIT (3): Quit with core dump
  • SIGKILL (9): Force kill (cannot be caught)
  • SIGTERM (15): Graceful termination (default)
  • SIGSTOP (19): Stop process
  • SIGCONT (18): Continue stopped process

killall and pkill

killall (by process name):

## Kill all processes with name
killall firefox

## Force kill
killall -9 nginx

## Send specific signal
killall -HUP syslogd

pkill (by pattern):

## Kill by pattern
pkill firefox

## Kill by user
pkill -u username

## Kill by parent PID
pkill -P PPID

## Send signal
pkill -HUP syslog

pgrep (find processes):

## Find process by name
pgrep firefox

## Show full [command line](https://terabyte.systems/posts/essential-linux-command-line-tools-daily-productivity/)
pgrep -a firefox

## Count matching processes
pgrep -c nginx

Process Priority and Nice Values

Understanding Nice Values

Nice values range from -20 (highest priority) to 19 (lowest priority). Default is 0.

  • Lower nice value = higher priority
  • Only root can use negative nice values
  • Regular users can only increase niceness (lower priority)

Setting Priority

nice (start with specific priority):

## Start with nice value 10
nice -n 10 command

## Start with lowest priority
nice -n 19 ./cpu-intensive-task

## Start with high priority (requires root)
sudo nice -n -10 ./important-task

renice (change running process priority):

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

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

## Change priority for process group
renice -n 5 -g PGID

Example:

## Find process
pgrep cpu-hog

## Lower its priority
renice -n 15 -p $(pgrep cpu-hog)

## Verify
ps -o pid,ni,cmd -p $(pgrep cpu-hog)

Finding and Filtering Processes

Using ps with grep

## Find nginx processes
ps aux | grep nginx

## Find processes by user
ps -u www-data

## Find zombie processes
ps aux | grep Z

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

## Find high memory processes
ps aux --sort=-%mem | head -10

Advanced ps Usage

## Custom output format
ps -eo pid,ppid,user,%cpu,%mem,cmd

## Process tree with PIDs
ps -ejH

## Process threads
ps -eLf

## Watch process continuously
watch -n 1 'ps aux | grep nginx'

Monitoring System Resources

CPU Usage

## Real-time CPU usage
top

## CPU info
cat /proc/cpuinfo

## Load average
uptime
w

## CPU usage by process
ps aux --sort=-%cpu | head -10

Memory Usage

## Memory summary
free -h

## Detailed memory info
cat /proc/meminfo

## Per-process memory
ps aux --sort=-%mem | head -10

## Memory map of process
pmap PID

I/O Statistics

## Install iotop
sudo apt install iotop

## Monitor I/O usage
sudo iotop

## I/O statistics
iostat -x 1

Working with Process Files

/proc Filesystem

Each process has a directory in /proc/PID/:

## Process info
cat /proc/PID/status

## Command line
cat /proc/PID/cmdline

## Environment variables
cat /proc/PID/environ | tr '\0' '\n'

## Current directory
ls -l /proc/PID/cwd

## Open files
ls -l /proc/PID/fd

## Memory maps
cat /proc/PID/maps

lsof (List Open Files)

## Install lsof
sudo apt install lsof

## Files opened by process
lsof -p PID

## Processes using file
lsof /path/to/file

## Network connections
lsof -i

## Specific port
lsof -i :80

## Files opened by user
lsof -u username

## Files in directory
lsof +D /var/log

Process Management Scripts

Kill Process by Name

#!/bin/bash
## kill-by-name.sh

PROCESS_NAME=$1

if [ -z "$PROCESS_NAME" ]; then
    echo "Usage: $0 process_name"
    exit 1
fi

PIDS=$(pgrep -x "$PROCESS_NAME")

if [ -z "$PIDS" ]; then
    echo "No process found: $PROCESS_NAME"
    exit 1
fi

echo "Found PIDs: $PIDS"
echo "Sending SIGTERM..."
kill $PIDS

sleep 2

## Check if still running
REMAINING=$(pgrep -x "$PROCESS_NAME")
if [ -n "$REMAINING" ]; then
    echo "Process still running. Sending SIGKILL..."
    kill -9 $REMAINING
fi

echo "Process terminated: $PROCESS_NAME"

Monitor High CPU Processes

#!/bin/bash
## monitor-cpu.sh

THRESHOLD=80

while true; do
    ps aux | awk -v threshold=$THRESHOLD '
    NR>1 && $3>threshold {
        printf "%s\t%s\t%s%%\t%s\n", $2, $1, $3, $11
    }' | while read pid user cpu cmd; do
        echo "[ALERT] High CPU: PID=$pid USER=$user CPU=$cpu% CMD=$cmd"
    done
    sleep 5
done

Automatic Process Restart

#!/bin/bash
## process-watchdog.sh

PROCESS="nginx"
RESTART_CMD="systemctl restart nginx"

while true; do
    if ! pgrep -x "$PROCESS" > /dev/null; then
        echo "[$(date)] Process $PROCESS not running. Restarting..."
        $RESTART_CMD
        sleep 5
        if pgrep -x "$PROCESS" > /dev/null; then
            echo "[$(date)] Process $PROCESS restarted successfully"
        else
            echo "[$(date)] Failed to restart $PROCESS"
        fi
    fi
    sleep 60
done

Troubleshooting Common Issues

Unresponsive Process

## Try graceful termination
kill PID

## Wait a few seconds
sleep 5

## Check if still running
ps -p PID

## Force kill if necessary
kill -9 PID

Zombie Processes

Zombie processes cannot be killed—they’re already dead. The parent process must reap them.

## Find zombies
ps aux | grep Z

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

## Kill parent (will reap zombie)
kill PARENT_PID

Too Many Processes

## Count processes by user
ps hax -o user | sort | uniq -c | sort -rn

## Limit processes with ulimit
ulimit -u 100  # Max 100 processes

## System-wide limit
cat /proc/sys/kernel/pid_max

High Load Average

## Check load average
uptime

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

## Find I/O-intensive processes
sudo iotop

## Check for D state processes (I/O wait)
ps aux | grep " D"

Best Practices

Process Management Best Practices

  1. Use graceful termination: Try SIGTERM before SIGKILL
  2. Monitor resource usage: Regular monitoring prevents issues
  3. Use process limits: Prevent resource exhaustion with ulimits
  4. Proper background execution: Use nohup for long-running tasks
  5. Log management: Redirect output appropriately
  6. Clean up zombies: Ensure proper process cleanup
  7. Priority management: Use nice for resource-intensive tasks
  8. Regular audits: Review running processes periodically

Security Considerations

  1. Check for unauthorized processes: Regularly audit running processes
  2. Monitor root processes: Pay attention to processes running as root
  3. Review listening ports: Check what processes are listening on network
  4. Limit user processes: Use ulimits to prevent fork bombs
  5. Secure /proc: Limit access to process information if needed

Quick Reference Commands

Essential Commands Cheat Sheet

## View processes
ps aux                     # All processes
ps -ef                     # Full format
pstree                     # Process tree
top                        # Interactive monitoring
htop                       # Enhanced top

## Find processes
pgrep process              # Find by name
pidof process              # Get PIDs
ps aux | grep pattern      # Search processes

## Kill processes
kill PID                   # Graceful termination
kill -9 PID                # Force kill
killall process            # Kill by name
pkill pattern              # Kill by pattern

## Job control
Ctrl+Z                     # Suspend
fg                         # Foreground
bg                         # Background
jobs                       # List jobs
disown                     # Remove from job table

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

## Resources
free -h                    # Memory usage
lsof -p PID                # Open files
netstat -tulpn             # Network connections

Conclusion

Process management is a core Linux administration skill. Understanding how to view, control, prioritize, and terminate processes enables effective system management and troubleshooting. From basic commands like ps and kill to advanced tools like htop and lsof, Linux provides comprehensive process management capabilities.

Regular monitoring, appropriate use of background execution, proper signal handling, and understanding process states are essential for maintaining healthy, responsive systems. Whether managing a single-user workstation or multi-user server, mastering process management ensures efficient resource utilization and system reliability.


References

Thank you for reading! If you have any feedback or comments, please send them to [email protected].