Chapter 7: Working with Processes in Linux

Working with processes in Linux

Process management is essential for system administration, debugging, and resource optimization. This chapter covers how to monitor, control, and prioritize running processes in Linux.


1. Viewing Processes (ps)

The ps command shows running processes.

Basic Usage

ps                 # Shows your current shell's processes
ps aux             # Detailed list of ALL running processes
ps -ef | grep nginx  # Find specific process

Key Columns in ps aux

ColumnMeaning
USERProcess owner
PIDProcess ID
%CPUCPU usage
%MEMMemory usage
COMMANDRunning command

2. Interactive Monitoring (tophtop)

top (Basic Process Viewer)

top
  • Key Controls:
    • q → Quit
    • Shift + M → Sort by memory
    • Shift + P → Sort by CPU
    • k → Kill a process (enter PID)

htop (Enhanced Version)

htop offers detailed and interactive information about system resources and processes running. You can filter information as well.

htop  
# Install with `sudo apt install htop` (if missing)
  • Colorful, scrollable, and mouse-friendly
  • Easily kill processes (F9) or sort (F6)

3. Killing Processes (killkillallxkill)

Graceful Termination

kill -15 PID      # Politely ask to stop (SIGTERM)
killall nginx     # Kill all processes named "nginx"

Force Kill (Use Sparingly)

kill -9 PID       # Brutal force kill (SIGKILL)
xkill             # GUI mode: click a window to kill it

4. Background Jobs (&jobsfgbg)

Run a Command in Background

long_running_command &  # Runs in background

Manage Background Jobs

jobs       # List background jobs
fg %1      # Bring job 1 to foreground
bg %2      # Resume job 2 in background
Ctrl + Z   # Suspend current foreground job

5. Process Priority (nicerenice)

Launch a Low-Priority Process

nice -n 19 cpu_intensive_task  # Lowest priority (19)
nice -n -20 critical_task      # Highest priority (-20)

Change Priority of Running Process

renice -n 10 -p PID  # Set priority to 10

Priority Range

ValueEffect
-20Highest priority
0Default
19Lowest priority


Practical Examples

Find and Kill a Frozen Process

ps aux | grep "bad_program" kill -9 [PID]

Monitor CPU-Hungry Processes

top -o %CPU # Sort by CPU usage

Run a Script in Background

./backup.sh &    # Runs the script in the background
jobs             # Lists all background jobs
fg               # Bring to foreground

# To stop or kill it manually, first find its PID:
ps aux | grep backup.sh

# Note Process it Then kill it: lets say process id is 50011
kill <50011>

Limit Resource Usage

nice -n 19 ./heavy_script.sh # Low priority

Summary Cheat Sheet

CommandDescription
ps auxList all processes
topLive process monitor
kill -9 PIDForce kill
command &Run in background
nice -n 5 cmdStart with low priority
renice -n 10 -p PIDChange priority