Skip to main content

⚙️ Lesson 6.1: Managing Processes

Every running program is a process. Learn to find them, monitor them, and — when necessary — end them.

🎯 Learning Objectives

  • Understand what a process is and how Linux tracks them
  • View running processes with ps, top, and htop
  • Send signals to processes with kill and killall
  • Manage foreground and background jobs
  • Find which process is using a port or file

Estimated Time: 40 minutes

📑 In This Lesson

What Is a Process?

Every program you run creates at least one process — an instance of a running program with its own memory, open files, and a unique PID (Process ID).

graph TD A["You type: firefox"] --> B["Kernel creates a process"] B --> C["Assigns PID: 4523"] B --> D["Allocates memory"] B --> E["Starts execution"] C --> F["Process runs until
it finishes or is killed"] style A fill:#3b82f6,stroke:#2563eb,color:#fff style B fill:#6366f1,stroke:#4338ca,color:#fff style F fill:#22c55e,stroke:#166534,color:#fff

Key concepts:

  • PID — a unique number identifying each process. PID 1 is always the init system (systemd on Ubuntu)
  • PPID — Parent PID: the process that spawned this one. Your terminal's shell is the parent of commands you type
  • State — running, sleeping (waiting for input/events), stopped, or zombie (finished but not yet cleaned up)
  • Owner — the user who started the process (affects what it can access)

Viewing Processes with ps

ps shows a snapshot of current processes. It's not real-time — it shows the state at the moment you run it.

# Show processes in the current terminal session
ps

# Show ALL processes (every user, with details)
ps aux

# Show processes in a tree (parent-child relationships)
ps auxf

# Show processes for the current user
ps -u $USER

# Show only specific columns
ps -eo pid,ppid,user,%cpu,%mem,comm --sort=-%cpu | head -20

Understanding ps aux Output

USER       PID %CPU %MEM    VSZ   RSS TTY   STAT START   TIME COMMAND
root         1  0.0  0.3 169464 13276 ?     Ss   09:00   0:02 /sbin/init
ray       4523  2.1  3.5 345600 142300 ?    Sl   09:15   1:23 /usr/bin/firefox
ray       4891  0.0  0.1  10456  5632 pts/0 Ss   09:20   0:00 bash
ColumnMeaning
USERProcess owner
PIDProcess ID
%CPUCPU usage percentage
%MEMMemory usage percentage
VSZVirtual memory size (KB)
RSSActual physical memory used (KB)
STATProcess state (S=sleeping, R=running, Z=zombie)
COMMANDThe command that started this process

💡 Piping ps with grep

The most common pattern — find a specific process:

# Find all firefox processes
ps aux | grep firefox

# Exclude the grep command itself from results
ps aux | grep [f]irefox

The bracket trick [f]irefox works because the grep process itself won't match the regex [f]irefox.

Real-Time Monitoring with top

top is the built-in real-time process monitor — it updates every few seconds (like Task Manager on Windows).

# Launch top
top

# Show only processes for your user
top -u $USER

Navigating Inside top

KeyAction
qQuit
hHelp
PSort by CPU usage
MSort by memory usage
kKill a process (prompts for PID)
1Toggle per-CPU core display
cToggle full command path
SpaceRefresh immediately

The top Header

top - 14:32:10 up  5:32,  2 users,  load average: 0.52, 0.38, 0.31
Tasks: 287 total,   1 running, 286 sleeping,   0 stopped,   0 zombie
%Cpu(s):  3.2 us,  1.1 sy,  0.0 ni, 95.4 id,  0.3 wa,  0.0 hi,  0.0 si
MiB Mem :  15924.3 total,   8234.1 free,   4512.6 used,   3177.6 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.  10890.2 avail Mem
  • Load average — 1-min, 5-min, 15-min averages. A value equal to your CPU count means 100% utilization
  • %Cpu us — user processes; sy — kernel/system; id — idle
  • MiB Mem — total, free, used, and buffered/cached RAM

htop — A Better top

htop is an improved, color-coded, interactive process viewer. It shows CPU and memory usage with visual bar graphs and supports mouse interaction.

# Install htop (if not already installed)
sudo apt install -y htop

# Run it
htop

htop Navigation

KeyAction
F1 or hHelp
F2Setup (customize display)
F3 or /Search for a process
F4 or \Filter processes
F5Tree view (show parent-child hierarchy)
F6Sort by column
F9Kill a process (choose signal)
F10 or qQuit
SpaceTag/select a process
uFilter by user
tToggle tree view

✅ Why htop Is Worth Installing

  • Color-coded CPU and memory bars at the top
  • Mouse support — click column headers to sort, click processes to select
  • Tree view to see which process spawned which
  • Easy search and filter without piping to grep
  • Scroll horizontally to see full command lines

Stopping Processes

Sometimes a program freezes or you need to stop a runaway process. Linux uses signals to communicate with processes.

Common Signals

SignalNumberMeaningBehavior
SIGTERM15TerminatePolitely asks the process to exit (default)
SIGKILL9KillForces immediate termination (can't be caught or ignored)
SIGSTOP19StopPauses the process (can't be caught)
SIGCONT18ContinueResumes a stopped process
SIGHUP1Hang upOften used to reload configuration
SIGINT2InterruptSame as pressing Ctrl+C

Using kill, killall, and pkill

# Send SIGTERM (graceful exit) — default signal
kill 4523

# Force-kill a stubborn process
kill -9 4523
# or equivalently:
kill -SIGKILL 4523

# Kill ALL processes with a given name
killall firefox

# Kill processes by partial name match
pkill fire

# Kill all processes owned by a user (DANGEROUS!)
# pkill -u username

⚠️ Always Try SIGTERM First

kill -9 (SIGKILL) should be your last resort. It kills the process instantly without letting it save data, close files, or clean up. Always try a regular kill PID first and wait a few seconds. Use kill -9 only when the process truly won't respond.

Keyboard Shortcuts for Active Processes

ShortcutSignalEffect
Ctrl+CSIGINTInterrupt (stop) the running command
Ctrl+ZSIGTSTPSuspend (pause) the running command
Ctrl+\SIGQUITQuit and dump core (hard stop)

Background and Foreground Jobs

You can run processes in the background to keep using your terminal while they work.

# Run a command in the background (add & at the end)
sleep 120 &
# Output: [1] 5678  (job number and PID)

# List background jobs in this terminal
jobs

# Bring a background job to the foreground
fg %1      # %1 = job number 1

# Suspend a foreground job with Ctrl+Z, then resume in background
# (press Ctrl+Z while something is running)
bg %1      # resume job 1 in background

# Run a command that survives closing the terminal
nohup long_running_script.sh &
# Output goes to nohup.out by default
graph LR A["Command running
in foreground"] -->|"Ctrl+Z"| B["Job suspended
(stopped)"] B -->|"bg %1"| C["Job running
in background"] C -->|"fg %1"| A A -->|"command &"| C style A fill:#3b82f6,stroke:#2563eb,color:#fff style B fill:#f59e0b,stroke:#b45309,color:#fff style C fill:#22c55e,stroke:#166534,color:#fff

💡 nohup and disown

Background jobs (started with &) still die when you close the terminal. To keep them running:

  • nohup command & — immune to hang-up signals from the start
  • disown %1 — detach an already-running background job from the terminal

For truly long-running tasks, consider using tmux or screen (terminal multiplexers) — covered in more advanced courses.

Finding Processes

# Find which process is using a specific port
sudo lsof -i :8080
# or:
sudo ss -tlnp | grep 8080

# Find which process has a specific file open
sudo lsof /var/log/syslog

# Find a process by name
pgrep -la firefox

# Count how many instances of a process are running
pgrep -c firefox

# Find the PID of a specific command
pidof bash

💡 The /proc Filesystem

Linux exposes process information as files in /proc/. Every process gets a directory named after its PID:

# See info about process 1 (systemd)
ls /proc/1/

# What command started it?
cat /proc/1/cmdline

# How much memory does it use?
cat /proc/1/status | grep VmRSS

This virtual filesystem is how tools like ps, top, and htop get their data.

Exercises

🏋️ Exercise 1: Explore Running Processes

  1. List your processes: ps aux | grep $USER | head -20
  2. Count total processes: ps aux | wc -l
  3. Find the top 5 CPU consumers: ps aux --sort=-%cpu | head -6
  4. Find the top 5 memory consumers: ps aux --sort=-%mem | head -6

🏋️ Exercise 2: Background Jobs

  1. Start a background job: sleep 300 &
  2. Start another: sleep 600 &
  3. List jobs: jobs
  4. Bring job 1 to foreground: fg %1
  5. Suspend it: Ctrl+Z
  6. Resume in background: bg %1
  7. Kill both: kill %1 %2

🏋️ Exercise 3: Process Signals

# Start a process
sleep 1000 &
# Note the PID from the output

# Try SIGTERM first
kill PID_HERE

# If it's still running (check with: jobs)
# Force kill:
kill -9 PID_HERE

🏋️ Exercise 4: htop Exploration

  1. Install and launch: sudo apt install -y htop && htop
  2. Press F5 for tree view — see which processes are children of others
  3. Press F6 and sort by MEM%
  4. Press / and search for "bash"
  5. Press u and filter to show only your user
  6. Press q to quit

Knowledge Check

❓ Question 1

What does PID stand for?

❓ Question 2

What's the difference between kill (SIGTERM) and kill -9 (SIGKILL)?

❓ Question 3

How do you send a running foreground process to the background?

❓ Question 4

Which tool provides a colorful, interactive, real-time process viewer with mouse support?

Summary

🎉 Key Takeaways

  • Every running program is a process with a unique PID
  • ps aux gives a snapshot; top and htop give real-time views
  • kill PID sends SIGTERM (gentle); kill -9 PID sends SIGKILL (forced)
  • Use & to run commands in the background; Ctrl+Z + bg to send running commands there
  • nohup or disown keeps background jobs alive after closing the terminal
  • lsof and pgrep help track down what's using a port, file, or resource

🍎 On macOS

ps, top, kill, lsof, pgrep, background jobs (&, Ctrl+Z, bg, fg), and nohup all work on macOS. Install htop via brew install htop. macOS also has Activity Monitor (a GUI process manager) in Applications → Utilities — similar to Task Manager on Windows.

🚀 What's Next?

Next up: checking your system's disk space, hardware, and resource usage — essential for keeping your Linux system healthy.