# Process Management and Job Control

> Chapter 6 of the Courseiva LPI-LPIC1 curriculum — https://courseiva.com/learn/lpi-lpic1/process-management

**Official objective:** 103.5 — Manage processes, control jobs, and use signals, ps, top, and kill commands.

## Introduction

Process management is the operating system’s way of juggling multiple running programmes efficiently, ensuring the system remains responsive even under heavy load. For someone studying LPIC-1, understanding how to inspect, prioritise, and terminate processes is a fundamental skill for administering a Linux system. It solves the problem of programmes competing for limited resources and gives you the power to control what happens when a programme misbehaves.

## The Restaurant Kitchen Analogy

When you start running a program on a Linux system, it creates a process – a running instance of that program. This is like a chef starting to cook a specific dish from a recipe. Just as a chef needs the right ingredients, a process needs memory and CPU time to execute. Managing these processes is like a head chef organising the kitchen so multiple dishes can be prepared efficiently without burning anything.

In a busy restaurant, you have orders (programs) coming in constantly. The head chef (the kernel) decides which chef (process) works on which order and for how long. Some tasks are urgent and need immediate attention – like a customer with an allergy – so the chef might stop chopping vegetables to handle it. In Linux, this is like the kernel sending a signal (an interrupt) to stop or change what a process is doing. For instance, the `kill` command sends a signal to a process, just like a head chef shouting "stop!" to a chef who's about to add salt to a dish that's already salty.

Then there's job control. Imagine the head chef telling a chef to put a dish aside (background it) while they focus on a more urgent one. Later, the chef brings that dish back to the stovetop (foregrounds it) to finish it. In Linux, you can run a program in the background using `&` at the end of the command, or suspend a running job with `Ctrl+Z` and resume it in the background with `bg` or foreground with `fg`. This prevents the kitchen – or your terminal – from getting blocked by one task.

So, process management and job control are the tools the head chef (the kernel) and you (the user) use to keep the kitchen running smoothly, prioritising urgent tasks and juggling multiple orders without chaos.

## Core explanation

A process is any running instance of a programme on a Linux system. When you type a command like `ls` or `cat`, the system creates a process to execute that command. Each process is identified by a unique number called a Process ID (PID). The kernel, which is the core of the operating system, manages these processes. It decides which process gets to use the CPU next and for how long. This decision-making is called scheduling.

You can see all the processes running on your system using the `ps` command. Without any options, `ps` shows only processes associated with your current terminal. To see every single process on the system, you use `ps aux`. The `a` option shows processes from all users, `u` gives a user-oriented format (including who owns the process and CPU/memory usage), and `x` shows processes without a controlling terminal (background daemons). The output includes several columns:
- PID: The unique process ID.
- USER: The user who owns the process.
- %CPU and %MEM: The percentage of CPU and memory the process is using.
- VSZ and RSS: Virtual and physical memory usage.
- STAT: The process state (e.g., S for sleeping, R for running, Z for zombie).
- COMMAND: The command that started the process.

Another popular tool is `top`, which gives a real-time, dynamic view of running processes. It updates every few seconds and sorts processes by CPU usage by default. You can press keys like `P` to sort by CPU, `M` to sort by memory, or `k` to kill a process by entering its PID. For a more modern alternative with better visuals, there is `htop`, but `top` is more commonly tested on the LPIC-1 exam.

Signals are the way the kernel communicates with processes. A signal is a software interrupt that tells a process to do something. The most common signal is SIGTERM (signal 15), which asks a process to terminate gracefully. If a process ignores SIGTERM, you can send SIGKILL (signal 9), which forces the process to stop immediately without any cleanup. The `kill` command sends a signal to a process by PID. For example, `kill -9 12345` sends SIGKILL to process 12345. You can also use `killall` to send a signal to all processes with a specific name, like `killall -9 firefox`.

Job control allows you to manage multiple tasks from a single terminal. When you run a command and add an ampersand (`&`) at the end, the command runs in the background. For example, `sleep 30 &` runs the sleep command in the background. The shell gives you a job number and a PID. You can suspend a running foreground job by pressing `Ctrl+Z`. This stops the job and puts it in a suspended state. The `jobs` command lists all the background and suspended jobs. The `bg` command resumes a suspended job in the background, while `fg` brings it back to the foreground.

Foreground processes tie up your terminal – you cannot run another command until they finish. Background processes run independently, allowing you to continue using the terminal for other commands. This is useful for long-running tasks like backups or compiling code. Job control numbers start from 1, and you refer to them with a percent sign, like `%1`.

Zombie processes are a special case. A zombie process is one that has finished executing but still has an entry in the process table because its parent process hasn't read its exit status. Zombies are harmless but indicate a programming issue in the parent. They are identified in `ps` output with a state of `Z`. The only way to remove them is to kill the parent process so the init process (PID 1) can clean them up.

The `nice` and `renice` commands control the priority of a process. The Linux kernel gives more CPU time to processes with a lower nice value. The nice value ranges from -20 (highest priority) to 19 (lowest priority). By default, processes run with a nice value of 0. Using `nice -n 10 ./myprogram` starts `myprogram` with a lower priority. The `renice` command changes the priority of an already running process: `renice +5 -p 12345` increases the nice value (lowering priority). Only the root user can set negative nice values (higher priority).

The `pstree` command shows processes in a tree-like structure, revealing which process is the parent of which. This helps visualise process dependencies.

Finally, the `uptime` and `w` commands show system load averages, which indicate how many processes are waiting to run on average over the last 1, 5, and 15 minutes. A load average above the number of CPU cores means the system is overloaded.

Understanding these concepts is crucial for the LPIC-1 exam because questions often ask you to interpret `ps` output, choose the correct signal to terminate a process, or explain the difference between foreground and background jobs.

## Real-world context

Imagine you are the sole system administrator for a small online store that runs on a Linux server. The store software includes a web server (Apache), a database (MySQL), and a payment processing script. One day, you receive alerts that the website is responding slowly. Your first step is to log in via SSH and run `top` to see what is consuming CPU and memory.

You see that a process called `php-cgi` (a PHP interpreter) is using 99% of the CPU and over 2GB of memory. The store's checkout page calls this script, and it seems to be stuck in an infinite loop. You note its PID, say 5678. You decide to try a graceful shutdown first, because if you force-kill it, you might lose a customer's order in the middle of processing. You run `kill 5678` (which sends SIGTERM). After a few seconds, the process is still there. You check `top` again – it remains at 99% CPU. That means the process is ignoring the gentle shutdown request.

Now you have no choice but to use SIGKILL. You type `kill -9 5678`. The process immediately disappears. The website speeds up. You then need to investigate why the script got stuck. You look in the Apache error logs and find a bug that causes an infinite loop under certain conditions.

Later, you need to run a full database backup that may take two hours. You don't want to sit and wait. So you start the backup script in the background: `./backup.sh &`. The shell returns a job number like [1] and a PID. You can check its progress with `jobs`. If you need to, you can suspend it with `Ctrl+Z` and then resume it in the background with `bg`. This lets you continue fixing other issues while the backup runs.

Another common task is adjusting process priority. Suppose a data analysis script is running but it's making the web server lag. You can lower its priority so it doesn't steal CPU time from the web server. You find its PID with `ps aux | grep analysis` and run `renice +10 -p 9876`. Now the analysis script uses spare CPU only when the web server isn't busy.

Zombie processes occasionally appear. You notice a zombie process in `ps aux` with state `Z`. You find its parent PID (PPID) and use `kill` on the parent. If the parent is a service, you may need to restart it. This keeps the process table clean.

Real-world process management also involves monitoring. You might set up a cron job (a scheduled task) that runs `ps` and `top` at intervals and logs unusual activity. You could also use `killall` to stop all processes of a particular user if you suspect a security breach.

In short, an IT professional uses these commands daily to troubleshoot slowdowns, manage long-running tasks, and ensure critical services stay responsive. The LPIC-1 exam expects you to be comfortable with all of these tools.

## Exam focus

The LPIC-1 exam objective 103.5 tests your ability to manage processes and control jobs. You can expect multiple-choice questions that ask you to interpret command output, choose the correct signal, or understand process states. Here is what you need to know precisely:

- Understanding `ps` output: Be able to read the columns PID, TTY, STAT, TIME, COMMAND. Know the meaning of process states: R (running or runnable), S (sleeping, interruptible), D (uninterruptible sleep, usually waiting for I/O), Z (zombie), T (stopped by job control signal). The exam often shows output and asks what state a process is in.

- Signals: Know the number and name of the most common signals: SIGHUP (1), SIGINT (2), SIGKILL (9), SIGTERM (15), SIGCONT (18), SIGSTOP (19). Be ready to answer which signal cannot be caught or ignored (SIGKILL and SIGSTOP). Know that `kill -l` lists all signal names.

- Job control: Understand that adding `&` at the end of a command runs it in the background. Know that `Ctrl+Z` suspends a foreground job. Understand the `jobs`, `bg`, and `fg` commands. Be able to bring a job to the foreground using `fg %1` where `%1` is the job number.

- The `kill` command: Understand that `kill` without a signal number sends SIGTERM by default. Know that `kill -9` forces termination. Be able to kill a process by its PID and by name using `killall`.

- Process priorities: Know that `nice` sets the scheduling priority when starting a process. Understand that `renice` changes the priority of an existing process. Remember that a lower nice value means higher priority. Know that only root can set negative nice values.

- `top` command: Know basic keys: `k` to kill a process, `r` to renice, `q` to quit, `P` to sort by CPU, `M` to sort by memory. Be able to identify the meaning of the load average values at the top of `top` output.

- Common traps: The exam may show a process in zombie state (Z) and ask how to remove it. The correct answer is to kill the parent process, not the zombie itself. Another trap: they might ask which signal a process cannot ignore. The answer is SIGKILL (9) and SIGSTOP (19). Another trap: they present `ps` output with a process in state D (uninterruptible sleep) and ask what it is waiting for – the answer is I/O (e.g., disk or network).

- Key definitions to memorise:
  - PID: Process identifier.
  - PPID: Parent process identifier.
  - Zombie process: A process that has terminated but still has an entry in the process table because the parent has not yet read its exit status.
  - Daemon: A background process that runs without a controlling terminal.
  - Fork: The system call used to create a new process.
  - Exec: The system call that replaces the current process with a new programme.

- Command line options: Know that `ps aux` is the most common combination. Understand that `ps -ef` is another common variant (System V style). `top` without options shows processes in real time. The `-u` option to `ps` shows processes for a specific user, like `ps -u student`.

Practise these commands in a terminal. The exam will test your ability to recall specific options and signal numbers, not just concepts. Flash cards for signal numbers (1, 2, 9, 15, 18, 19) and their names are highly recommended.

## Step by step

1. **Identify a running process** — Use `ps aux` to list all processes. The output includes PID, USER, %CPU, %MEM, and COMMAND. This is the first step in diagnosing any process-related issue.
2. **Analyse the process state** — Look at the STAT column. An 'R' means running, 'S' means sleeping, 'Z' means zombie. Understanding the state tells you what the process is doing and whether it is healthy.
3. **Send a signal to the process** — Use `kill PID` to send SIGTERM. If the process does not stop, use `kill -9 PID` to force termination. This step is critical when a process is unresponsive or consuming too many resources.
4. **Run a command in the background** — Add `&` to the end of a command, like `./longtask &`. Then use `jobs` to see the job number. This allows you to continue working while the task runs.
5. **Suspend and resume a job** — Press `Ctrl+Z` while a command is running in the foreground to suspend it. Then use `bg` to resume it in the background or `fg` to bring it back to the foreground. This gives you fine-grained control over task execution.
6. **Adjust process priority** — Find the PID of a process that is too aggressive with CPU using `ps`. Then use `renice +10 -p PID` to lower its priority. This helps maintain system responsiveness for critical services.

## Comparisons

### Foreground Process vs Background Process

**Foreground Process:**
- Blocks the terminal until it finishes
- Ties up the command prompt so you cannot run other commands
- Example: running `sleep 30` without &

**Background Process:**
- Runs independently without blocking the terminal
- Lets you continue typing and running other commands
- Example: running `sleep 30 &` with &

### SIGTERM (Signal 15) vs SIGKILL (Signal 9)

**SIGTERM (Signal 15):**
- Requests graceful termination
- Can be caught, handled, or ignored by the process
- Allows process to clean up resources before exiting

**SIGKILL (Signal 9):**
- Forces immediate termination
- Cannot be caught, handled, or ignored
- Does not allow any cleanup; kills the process instantly

### Zombie Process vs Orphan Process

**Zombie Process:**
- Process has terminated but entry remains in process table
- Parent has not yet read exit status
- Cannot be killed; only parent can clean it

**Orphan Process:**
- Process whose parent has terminated before it
- The orphan is adopted by init (PID 1)
- Init will automatically clean it up when it terminates

### nice Command vs renice Command

**nice Command:**
- Sets priority when starting a new process
- Syntax: nice -n value command
- Works with new processes only

**renice Command:**
- Changes priority of an existing running process
- Syntax: renice value -p PID
- Works with processes already in memory

### ps Command vs top Command

**ps Command:**
- Shows a static snapshot of processes at a point in time
- Common option: ps aux
- Does not update automatically

**top Command:**
- Shows a dynamic, real-time view of processes
- Updates every few seconds
- Allows interactive commands like k (kill) and r (renice)

## Diagram

_This flowchart illustrates the lifecycle of a Linux process from creation to termination, including job control and zombie states._

```mermaid
flowchart TD
    A[User types command] --> B[Shell creates process]
    B --> C[Process gets unique PID]
    C --> D{Kernel schedules process}
    D --> E[Foreground process blocks terminal]
    D --> F[Background process runs independently]
    F --> G[Use 'jobs' to list background jobs]
    G --> H[Use 'fg' to foreground a job]
    E --> I[Ctrl+Z suspends foreground job]
    I --> J[Use 'bg' to resume in background]
    C --> K[Process terminates]
    K --> L{Parent reads exit status?}
    L -->|Yes| M[Process removed from table]
    L -->|No| N[Process becomes zombie]
    N --> O[Kill parent process to clean zombie]
```

## Common misconceptions

- **Misconception:** The `kill` command permanently destroys a process and deletes it from memory. **Reality:** `kill` sends a signal to a process, which may cause it to terminate gracefully (SIGTERM) or immediately (SIGKILL). The process's memory is reclaimed by the kernel after termination, but `kill` does not delete any files or code. (The word 'kill' sounds violent, so beginners assume it obliterates everything. In reality, it is simply a way to communicate with a process via signals.)
- **Misconception:** A zombie process is dangerous and actively consuming system resources like CPU or memory. **Reality:** A zombie process holds only an entry in the process table; it does not use CPU or memory beyond that small table entry. It is not harmful but indicates a bug in the parent process that hasn't called `wait()`. (The name 'zombie' suggests something undead and harmful. But in Linux, a zombie is more like a corpse that hasn't been buried – it's inert.)
- **Misconception:** You can kill a zombie process directly with `kill -9` because it's still running. **Reality:** A zombie is already dead – it has terminated. The `kill` command cannot target it because there is no process to signal. You must kill the parent process to clean up the zombie. (New users see a zombie in the process list and assume it's a process that needs to be killed, not one that has already exited.)
- **Misconception:** Background processes cannot be suspended with Ctrl+Z because they are not in the foreground. **Reality:** You can suspend a background process using the `kill -STOP` signal, or you can bring it to the foreground with `fg` and then press `Ctrl+Z`. Background processes can be stopped just like foreground ones. (Beginners think `Ctrl+Z` only works on the current foreground job. They forget that any process can receive the SIGSTOP signal.)
- **Misconception:** A higher nice value gives a process higher priority. **Reality:** In Linux, a lower nice value means higher priority. The nice value ranges from -20 (most favourable, highest priority) to 19 (least favourable, lowest priority). (The word 'nice' implies being nice to the system, but the numerical inverse is confusing. People naturally assume a larger number means more priority.)
- **Misconception:** Using `killall` kills all processes on the system. **Reality:** `killall` sends a signal to all processes that match a given name. For example, `killall firefox` kills only Firefox processes, not everything. Without specifying a name, `killall` does nothing or uses the default name if one is provided. (The name 'killall' sounds like it would terminate everything. In reality, it requires a process name argument.)

## Key takeaways

- Every running programme on Linux creates at least one process, identified by a unique PID.
- The `ps aux` command shows all processes on the system with detailed information about CPU, memory, and ownership.
- SIGTERM (signal 15) asks a process to terminate gracefully, while SIGKILL (signal 9) forces immediate termination without cleanup.
- You can run a command in the background by appending an ampersand (&) to the command, freeing up the terminal.
- The `nice` and `renice` commands control process priority, where a lower nice value means higher priority.
- Zombie processes are harmless entries in the process table that require the parent process to clean them up.
- The `jobs`, `bg`, and `fg` commands let you manage multiple tasks from one terminal session.
- Only the root user can set a negative nice value, giving a process higher than default priority.

## FAQ

**What is the difference between a process and a programme?**

A programme is a file stored on disk (e.g., an executable), while a process is an instance of that programme running in memory. One programme can have multiple processes.

**How do I see all processes running on my Linux system?**

Use the `ps aux` command. It shows all processes from all users, including those without a terminal, with details on CPU and memory usage.

**What does `kill -9` do that `kill` without options doesn't?**

`kill` without options sends SIGTERM (signal 15), asking the process to terminate gracefully. `kill -9` sends SIGKILL, which forces the process to stop immediately without any cleanup.

**How do I run a command in the background and keep using the terminal?**

Append an ampersand (`&`) to the end of the command, like `sleep 100 &`. The shell returns a job number and a PID, and the command runs in the background.

**What is a zombie process and how do I remove it?**

A zombie process is one that has exited but still has an entry in the process table because its parent hasn't read its exit status. To remove it, kill the parent process (PPID) so init cleans up the zombie.

**How do I change the priority of a running process?**

Use `renice` followed by a new nice value and the PID. For example, `renice +10 -p 12345` lowers the priority of process 12345. Lower nice values mean higher priority.

## Check your understanding

1. **What command shows all running processes on the system with detailed CPU and memory usage?**

   Answer: `ps aux` shows all processes from all users with CPU, memory, and other details.

2. **Which signal number corresponds to SIGKILL and what does it do?**

   Answer: Signal 9 (SIGKILL) forces a process to terminate immediately without any cleanup.

3. **How do you run a command in the background so the terminal remains usable?**

   Answer: Append an ampersand (&) to the end of the command, for example: `sleep 60 &`.

4. **What is the difference between a process in state R and a process in state Z?**

   Answer: State R means the process is currently running or runnable, while state Z means the process is a zombie (terminated but still in the process table).

5. **How can you change the priority of an already running process?**

   Answer: Use the `renice` command with the new nice value and the process's PID, for example: `renice +10 -p 12345`.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/lpi-lpic1/process-management
