Chapter 4.3 - Process Control
Learning Objectives
By the end of this chapter, you will be able to:
- Start processes
- Stop and kill processes
- Suspend and resume
- Manage background processes
- Understand signals
Starting a Process
Command Line
# Foreground process
command
# Background process
command &
# Example
sleep 60 &
nohup - Ignore SIGHUP
# Continue after logout
nohup command &
# Redirect output
nohup command > output.log 2>&1 &
Stopping a Process
kill - Send a Signal
# TERM signal (graceful termination)
kill PID
kill -TERM PID
kill -15 PID
# KILL signal (forced)
kill -9 PID
kill -KILL PID
# By name
killall process_name
killall -9 process_name # Force
# By pattern
pkill pattern
pkill -9 pattern
Common Signals
| Signal | Number | Action |
|---|---|---|
| SIGHUP | 1 | Hang up (reload config) |
| SIGINT | 2 | Interrupt (Ctrl+C) |
| SIGQUIT | 3 | Quit (core dump) |
| SIGTERM | 15 | Terminate (graceful) |
| SIGKILL | 9 | Kill (forced, cannot be ignored) |
| SIGSTOP | 19 | Stop (suspend) |
| SIGCONT | 18 | Continue (resume) |
Suspending and Resuming
Suspend
# Send SIGSTOP
kill -STOP PID
kill -19 PID
# Or with Ctrl+Z in the terminal
# (suspends the foreground process)
Resume
# Send SIGCONT
kill -CONT PID
kill -18 PID
# Foreground
fg
# Background
bg
Background Processes
jobs - View Jobs
# View jobs
jobs
# With PIDs
jobs -l
# Also completed jobs
jobs -a
fg and bg
# Bring to foreground
fg
fg %1 # Job number 1
fg %name # Job by name
# Send to background
bg
bg %1
disown - Detach a Job
# Detach from terminal
disown %1
disown -h %1 # Do not send SIGHUP
Practical Examples
Scenario 1: Unresponsive Process
# 1. Find the PID
ps aux | grep process
# 2. Try graceful
kill PID
# 3. Wait a few seconds
sleep 5
# 4. If still there, force
kill -9 PID
Scenario 2: Background Process
# Start in background
long_script.sh &
# View jobs
jobs
# Bring to foreground
fg %1
# Suspend (Ctrl+Z)
# Resume in background
bg %1
Scenario 3: Process Continues After Logout
# With nohup
nohup long_task.sh > output.log 2>&1 &
# Or with screen/tmux
screen -S session
# Start process
# Detach: Ctrl+A then D
# Reattach: screen -r session
Signals and Their Usage
SIGTERM (15) - Graceful Termination
kill -TERM PID
# The process can:
# - Save data
# - Close files
# - Clean up resources
SIGKILL (9) - Forced Termination
kill -9 PID
# The process:
# - Cannot be ignored
# - Is killed immediately
# - No cleanup possible
Use only if SIGTERM does not work!
SIGHUP (1) - Reload Configuration
# Often used to reload config
kill -HUP PID
# Example: reload nginx
kill -HUP $(pidof nginx)
Summary
In this chapter, you learned:
Start: command, command &, nohup
Stop: kill, killall, pkill with signals
Signals: TERM (graceful), KILL (forced), HUP (reload)
Suspend: SIGSTOP, Ctrl+Z
Resume: SIGCONT, fg, bg
Background: jobs, fg, bg, disown
Next Steps
Chapter 4.4: Priorities and Nice Values
Chapter 4.5: Processes and Resources
Chapter created on: December 2024