# Process Management and System Monitoring

> Chapter 6 of the Courseiva LINUX-PLUS curriculum — https://courseiva.com/learn/linux-plus/process-management-and-system-monitoring

**Official objective:** 2.2 — Monitor and manage system processes and resources

## Introduction

Process management and system monitoring are the tools your Linux computer uses to decide which program gets to use the CPU first, for how long, and what happens when a program crashes. For the XK0-006 exam, you must understand how to inspect, prioritise, and terminate processes because every real-world Linux job requires you to troubleshoot misbehaving software and keep systems running efficiently.

## The Kitchen Ticket System Analogy

A busy restaurant kitchen gets a flood of customer orders (the equivalent of new tasks or programs to run). This leads to the head chef needing a system to manage every ticket without burning the toast or forgetting a steak. In a kitchen, every new ticket is like a new process created by the operating system. The chef uses a ticket rail to keep orders in sequence, much like a process queue. Each ticket lists specific ingredients and cooking steps, just as a process has its own allocated memory, priority, and execution thread. When the chef sees a ticket for a well-done steak that takes forty minutes, they set it aside and start on a salad that takes two minutes. This is exactly how CPU scheduling works: the kernel gives a high priority to quick, interactive tasks (like typing in a terminal) while background work (like a system update) waits its turn. If a ticket becomes impossible to complete because the kitchen ran out of a key ingredient, the chef marks it as stopped and throws it away. The computer equivalent is a Zombie process, where the parent process forgot to collect the exit status of its child. monitoring the kitchen means the chef constantly checks the ticket rail for stuck orders, just as a system administrator uses the `ps` command to list running processes and `kill` to terminate a misbehaving one. The kitchen analogy breaks if you imagine a single cook handling every dish at once; in reality, modern computers use multiprocessing with many cores, but the underlying management of individual tasks is identical.

Finally, the chef uses a digital display board to see all active tickets at a glance. This board is the Linux `top` utility, showing real-time CPU and memory usage, and allowing the chef to reprioritise a task that has become urgent. Mastering process management means you can keep your operating system kitchen running smoothly, no matter how many orders come in.

## Core explanation

A process is simply a program that is currently executing. When you double-click a text editor or run a command in the terminal, the Linux kernel (the core of the operating system) creates a process for that task. Each process has a unique identifier called a PID (Process ID), which is just a number you can use to reference that specific process later. Processes also have a parent process that created them, forming a tree structure that starts with the first process, `init` (or `systemd` on modern systems).

Every process needs resources: CPU time, memory, and access to files. The kernel is the traffic controller. It uses a scheduler to decide which process gets the CPU at any moment. Without a scheduler, a single program could hog the CPU forever and the whole system would freeze. The scheduler uses priorities to make this decision. A process with a higher priority gets more CPU time than one with a lower priority. You can see the priority of a process as its `nice` value. The nice value ranges from -20 (highest priority) to +19 (lowest priority). By default, most processes run with a nice value of 0. You can change a running process’s nice value using the `renice` command, which is useful when a background task is slowing down your interactive work.

Linux processes exist in different states. The main ones you need to know for XK0-006 are:
- Running (R): the process is currently using the CPU or is ready to use it.
- Sleeping (S): the process is waiting for something, like user input or data from a disk.
- Stopped (T): the process has been paused by a signal, usually by pressing Ctrl+Z in the terminal.
- Zombie (Z): the process has finished executing but still has an entry in the process table because its parent has not read its exit status. Zombie processes do not consume CPU or memory, but a large number of them signals a buggy parent program.

To see all running processes, you use the `ps` command. `ps aux` shows every process on the system with detailed columns: user, PID, CPU and memory usage, and the command that started it. The `top` command gives a live, updating view of processes sorted by resource usage. From `top`, you can press `k` to kill a process or `r` to change its priority.

Signals are how the operating system tells a process to do something. The most common signals are:
- SIGTERM (signal 15): asks a process to terminate gracefully. The process can clean up its files and shut down.
- SIGKILL (signal 9): forces a process to stop immediately. The process cannot ignore this signal. Use this only when SIGTERM fails.
- SIGSTOP (signal 19): pauses a process.
- SIGCONT (signal 18): resumes a paused process.

To send a signal to a process, you use the `kill` command followed by the PID. For example, `kill -15 1234` sends SIGTERM to process 1234. `kill -9 1234` sends SIGKILL. You can also use `killall` to send a signal to all processes with a given name, like `killall -9 firefox`.

System monitoring goes beyond processes. You need to check overall system health. The `free` command shows memory usage. The `df` command shows disk space usage. The `uptime` command tells you how long the system has been running and the average load on the CPU over 1, 5, and 15 minutes. The `dmesg` command shows kernel ring buffer messages, which include hardware errors and device driver issues. All of these are part of monitoring a Linux system.

Why does process management exist? Before operating systems had multitasking, a computer could only run one program at a time. If you started a long calculation, you could not do anything else until it finished. Modern operating systems use preemptive multitasking: the kernel interrupts a running process after a tiny time slice (a few milliseconds) and gives the CPU to the next process. This makes it feel like many programs are running at once, even on a single-core processor. The scheduler decides which process runs next based on priority and recent CPU usage.

When you are studying for Linux+, you must also understand foreground and background processes. When you run a command in the terminal, it runs in the foreground and blocks the shell until it finishes. You can send it to the background by appending `&` to the command: `sleep 100 &`. The shell returns immediately, and you can run other commands. The `jobs` command shows your background processes. The `fg` command brings one back to the foreground. The `bg` command resumes a stopped background process.

## Real-world context

A junior Linux administrator at a small e-commerce company gets an alert at 2:00 AM that the company website is responding very slowly. They SSH (secure shell) into the server to investigate.

First, they run `top` to see what is consuming resources. They see that a process called `virus_scan` is using 95% of the CPU. The web server process `apache2` is using only 1%. This is the problem: a scheduled virus scan is hogging the CPU, making the web server slow to respond to customer requests.

The administrator needs to fix this immediately. They can either kill the virus scan or lower its priority so the web server gets more CPU time. They choose to lower the priority. They find the PID of `virus_scan` from the `top` display (e.g., PID 4567). They run `renice +10 -p 4567`. This raises the nice value, making the virus scan less important. Instantly, the web server processes start getting more CPU time, and the website speeds back up.

After the immediate fix, the administrator investigates why the virus scan was running during peak business hours. The scheduled cron job (a time-based job scheduler) was set to run at 2:00 AM, which should have been safe, but the server clock was wrong due to a failing CMOS battery. The administrator fixes the clock and updates the cron schedule to run during the lowest traffic period the next day.

Later, they monitor the system using `ps aux --sort=-%mem` to check memory usage and ensure no other processes are leaking memory. They see a web server child process `apache2` using 2GB of memory, far above normal. This is a memory leak. They use `kill -15` on that child PID, and Apache automatically spawns a new, healthy child process. The administrator then files a bug report with the web development team about the memory leak.

In a more serious scenario, a process might become unresponsive to SIGTERM. The administrator must then use SIGKILL (`kill -9 PID`). This is a last resort because it does not give the process a chance to save data. For example, if a database server process freezes and will not respond to any command, the administrator will force-kill it and then restart the database service.

Every real Linux admin uses these tools daily. The skill is knowing which tool to use and when. The exam expects you to be able to interpret the output of `ps`, `top`, and `free` and take appropriate action.

## Exam focus

XK0-006 tests process management and system monitoring heavily. Expect at least 8–12 questions on this objective. The exam loves scenario-based questions where you are shown the output of `ps`, `top`, `free`, or `df` and asked to identify the problem and the correct command to fix it.

Key topics they test:
- Interpreting `ps aux` output: you must know what each column means (USER, PID, %CPU, %MEM, VSZ, RSS, STAT, START, TIME, COMMAND). The STAT column is particularly tricky. They will show a Zombie process (STAT Z) and ask what it means.
- Sending signals: they will ask which signal to use to terminate a process gracefully (SIGTERM) and which to use when it refuses to stop (SIGKILL). A common trap is asking for the signal that allows a process to clean up before exiting: that is SIGTERM, not SIGKILL.
- Nice values and priority: they will ask how to lower the priority of a running process (use `renice` with a positive nice value) or how to start a process with low priority (use `nice -n 10 command`). The trap: remembering that a higher nice value means lower priority.
- Background and foreground jobs: they will test the difference between running a command with `&`, using `fg` and `bg`, and the `jobs` command. A common question: you started a process in the foreground, you want to pause it and send it to the background. The correct sequence is Ctrl+Z to pause, then `bg` to resume in the background.
- System monitoring commands: `free -m` for memory in megabytes, `df -h` for disk space in human-readable format, `uptime` for load average. The load average is a 1-minute, 5-minute, and 15-minute average of processes waiting for CPU. A trap: a load average of 5 does not mean 5% CPU usage; it means 5 processes are waiting, which could be normal on an 8-core system but bad on a single-core system.
- Process states: they will ask to identify a sleeping process (STAT S), a running process (R), and a zombie process (Z).

Common exam traps:
- Confusing `nice` and `renice`: `nice` sets the priority when starting a process; `renice` changes it on a running process.
- Thinking that killing a parent process automatically kills all children. In Linux, children can become orphaned and are then adopted by `init` (PID 1).
- Believing that `kill -9` is the first solution. The exam expects you to try SIGTERM first.
- Misreading `top` output: the highest CPU usage is not always the problem—a process using 100% of one CPU core might be fine, but a process causing the load average to spike across all cores is a problem.
- Forgetting the PID: many questions give you a process name and expect you to use `pidof` or `pgrep` to find its PID before using `kill`.

Definitive command list to memorise for the exam:
- `ps aux`
- `ps -ef`
- `top`
- `htop` (though less common on exam)
- `kill [-signal] PID`
- `killall [-signal] name`
- `nice -n value command`
- `renice -n value -p PID`
- `free -h`
- `df -h`
- `uptime`
- `jobs`
- `fg`
- `bg`
- `nohup command &` (run command immune to hangup signal)

## Step by step

1. **Identify the problem process** — Run `top` to see which process is using the most CPU or memory. Note its PID and name. This is the first step in any process management task because you cannot fix what you cannot see.
2. **Adjust the process priority** — If a background task is slowing down critical work, use `renice +10 -p PID` to lower its priority. This gives the CPU more time to other processes without killing the task entirely.
3. **Send a termination signal** — If the process is unresponsive, first try `kill -15 PID` (SIGTERM) to allow it to shut down cleanly. If it does not stop within a few seconds, use `kill -9 PID` (SIGKILL) as a last resort.
4. **Verify the process has stopped** — Run `ps aux | grep process_name` or check `top` again to ensure the process is no longer running. If it keeps reappearing, it may be a daemon that auto-restarts, and you need to stop the service instead.
5. **Monitor system resources** — After resolving the immediate issue, use `free -h` for memory, `df -h` for disk, and `uptime` for load average. Look for anomalies like high swap usage or disk space near capacity that could cause future problems.
6. **Document the incident** — Log the PID, the signal used, the time, and the outcome. In an organisation, this creates a record for incident response and helps identify recurring issues. The exam does not test documentation, but real-world practice requires it.

## Comparisons

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

**SIGTERM (signal 15):**
- Allows the process to clean up files and release resources gracefully.
- Can be caught or ignored by the process.
- The recommended first attempt to terminate a process.

**SIGKILL (signal 9):**
- Forces immediate termination with no cleanup.
- Cannot be caught or ignored by the process.
- Use only when SIGTERM fails or the process is unresponsive.

### Foreground process vs Background process

**Foreground process:**
- Runs in the current terminal and blocks further input until it finishes.
- You can stop it with Ctrl+C or suspend it with Ctrl+Z.
- Job number is shown when you use `fg` to bring it back.

**Background process:**
- Runs without blocking the terminal; you can type new commands immediately.
- Started by appending `&` to the command or using `bg` after Ctrl+Z.
- Managed with `jobs`, `fg`, and `bg` commands.

### nice command vs renice command

**nice command:**
- Used to start a new process with a specified priority.
- Syntax: `nice -n value command`.
- Only affects the process being launched.

**renice command:**
- Used to change the priority of an already running process.
- Syntax: `renice -n value -p PID`.
- Affects a process that is already in execution.

### Zombie process vs Orphan process

**Zombie process:**
- A process that has finished execution but still has an entry in the process table.
- Exists because its parent has not read its exit status.
- Uses negligible resources but can fill the process table if many exist.

**Orphan process:**
- A process whose parent has terminated before it did.
- Adopted by the init process (PID 1), which waits for it normally.
- Does not cause system problems and is cleaned up automatically.

## Diagram

_A flowchart showing the lifecycle of a Linux process from creation through states to termination._

```mermaid
flowchart TD
    A[User runs program] --> B[Kernel creates process with PID]
    B --> C[Process states]
    C --> D[Running R]
    C --> E[Sleeping S]
    C --> F[Stopped T]
    C --> G[Zombie Z]
    B --> H[CPU Scheduler assigns CPU time based on priority]
    H --> I[Process uses memory and CPU]
    I --> J{Process finishes or needs termination?}
    J -- Yes --> K[Process exits, reports to parent]
    J -- No --> H
    K --> L[Parent reads exit status, zombie removed]
```

## Common misconceptions

- **Misconception:** A zombie process is harmful and consuming CPU or memory. **Reality:** A zombie process has already finished executing and uses almost no system resources. It only occupies a small entry in the process table until its parent reads its exit status. (The name 'zombie' sounds scary, so beginners assume it is actively consuming resources. In reality, it is harmless unless there are thousands of them filling the process table.)
- **Misconception:** Using `kill -9` (SIGKILL) is always the best way to stop a program because it works instantly. **Reality:** SIGKILL should be a last resort because it does not allow the process to save data or release resources properly. Always try SIGTERM (kill -15) first. (New users want the quickest solution, and SIGKILL feels definitive. They do not realise it can corrupt data files or leave the system in an inconsistent state.)
- **Misconception:** A higher nice value means a process gets more CPU time (higher priority). **Reality:** The nice value is an inverse priority. A higher number (e.g., +19) means the process is nicer to others and gets less CPU time. A lower number (e.g., -20) means higher priority. (The word 'nice' suggests being generous, so beginners assume a high 'nice' is good for the process, but it actually lowers its own priority.)
- **Misconception:** The `ps` command shows all processes on the system, including system processes, without any options. **Reality:** Running `ps` alone only shows processes associated with the current terminal session. You must use options like `aux` or `-ef` to see all processes system-wide. (Beginners type `ps` and see only a few processes, then think that is the entire list. They do not understand that Linux separates user processes from background system processes.)
- **Misconception:** If you close a terminal window, all processes started from that terminal are automatically terminated. **Reality:** By default, processes are sent a SIGHUP signal when the terminal closes, which often terminates them. However, you can use the `nohup` command or `disown` to keep them running after logout. (It seems logical that closing the window would end things, but Linux gives you tools to decouple processes from their parent terminal.)

## Key takeaways

- Every running program is a process with a unique PID, and you can view all processes with `ps aux`.
- The CPU scheduler uses priority (nice values) to decide which process runs next, with lower nice values meaning higher priority.
- Always try SIGTERM (signal 15) before SIGKILL (signal 9) to stop a process gracefully.
- A zombie process is a finished process whose parent has not read its exit code; it uses negligible resources but indicates a buggy parent.
- The `free -h` command shows memory usage, and `df -h` shows disk space usage, both essential for system monitoring.
- You can run a command in the background with `&` and manage it using `jobs`, `fg`, and `bg`.
- The load average from `uptime` shows the number of processes waiting for CPU over 1, 5, and 15 minutes.

## FAQ

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

A process is any running instance of a program. A service (also called a daemon) is a process that runs in the background, usually started at boot, and provides a specific function like a web server or database.

**How do I find the PID of a process by name?**

Use `pgrep process_name` or `pidof process_name`. For example, `pgrep apache2` returns the PID(s) of all Apache processes.

**What does the load average number in `uptime` really mean?**

It shows the average number of processes waiting to run over 1, 5, and 15 minutes. A load average of 1 on a single-core CPU means the CPU is fully utilised. On a quad-core CPU, a load of 4 means all cores are busy.

**Can I kill a process if I do not know its PID?**

Yes, use `killall process_name` to kill all processes with that name. For example, `killall firefox` terminates all Firefox instances. Use caution because this kills every process matching the name.

**What is a daemon process?**

A daemon is a background process that is not connected to a terminal. It runs continuously, often starting at boot, to provide services like printing (cupsd) or web serving (httpd).

**How do I stop a process that is running in the background?**

Use `jobs` to see its job number, then `kill %jobnumber` to stop it. Alternatively, bring it to the foreground with `fg %1` and then press Ctrl+C.

## Check your understanding

1. **Which command shows a real-time, updating view of running processes sorted by CPU usage?**

   Answer: The `top` command displays a live view of processes sorted by CPU or memory usage.

2. **What signal number should you use to ask a process to terminate gracefully?**

   Answer: Signal 15 (SIGTERM) asks a process to shut down cleanly, allowing it to save data and release resources.

3. **If a process has a nice value of +10, does it have higher or lower priority than a process with a nice value of 0?**

   Answer: It has lower priority. A higher nice value means the process yields CPU time to others.

4. **What command would you use to check how much free disk space is available on all mounted filesystems in human-readable format?**

   Answer: The `df -h` command shows disk space in gigabytes or megabytes for each mounted partition.

5. **How do you run the command `long_script.sh` in the background so you can continue using the terminal?**

   Answer: Append an ampersand to the command: `./long_script.sh &`. The shell immediately returns the prompt.

---

Interactive version with quiz and diagrams: https://courseiva.com/learn/linux-plus/process-management-and-system-monitoring
