# Processes: see them, control them, stop them

What a process is, how to find the one eating your CPU, run jobs in the background, keep them alive after logout, stop them with the right signal and change their priority.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 7. About 30 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/07-process-management

## What you will learn

- Explain what a process is, and read PID, PPID, user, state and resource use
- Find processes with ps, top and pgrep, sorted by CPU or memory
- Run, pause, resume and background jobs, and keep work alive after logout
- Stop processes with the right signal, gently first, by force only when needed
- Lower or raise a process's priority with nice and renice
- Explain fork and exec, and why the process tree starts at PID 1

## What a process is

A program is a file on disk, such as `/usr/sbin/nginx`. A **process** is that program running:
it has memory, open files, a user it runs as, and a number, the **PID**. Run the same program
twice and you get two processes.

Every process is started by another one, its **parent** (PPID). On Linux that happens in two
steps: the parent **forks** (makes a copy of itself), and the copy **execs** (replaces itself with
the new program). So everything forms one family tree, rooted at **PID 1**, which on modern
servers is systemd.

> **Figure.** A process tree. systemd is PID 1. It started sshd and nginx. sshd started your SSH session, which runs bash, PID 2210. When you type a command, bash forks a copy of itself, and the copy execs the program, here grep, PID 2287, whose parent is 2210. nginx runs a master process with worker processes under it.
>
> Every process has a parent. Your commands are children of your shell.

```sh
$ echo $$                       # your shell's own PID
2210
$ bash -c 'echo "me=$$ parent=$PPID"'
me=2291 parent=2210
$ pstree -p | head -n 12        # the whole family tree
```

## Finding processes

```sh
$ ps aux                         # every process: user, PID, %CPU, %MEM, state, command
$ ps aux --sort=-%cpu | head -5  # the five busiest by CPU (-%mem for memory)
$ ps -ef | grep [n]ginx          # parent PIDs too. [n] stops grep matching itself
$ ps -o pid,ppid,user,ni,stat,%cpu,%mem,cmd -p 812   # exactly the columns you want
$ pgrep -a nginx                 # PIDs and command lines matching a name
812 nginx: master process /usr/sbin/nginx
813 nginx: worker process
$ pgrep -u www-data              # by user
```

The **STAT** column says what each process is doing:

| STAT | Means                                                                              |
| ---- | ---------------------------------------------------------------------------------- |
| `R`  | running, or ready to run                                                           |
| `S`  | sleeping, waiting for something (most processes, most of the time)                 |
| `D`  | waiting for the disk or network, and can't be interrupted. Many `D` = slow storage |
| `T`  | stopped (you pressed Ctrl+Z)                                                       |
| `Z`  | zombie: finished, but its parent hasn't collected it yet                           |

### top: the live view

`top` refreshes every few seconds. The keys that matter: **P** sort by CPU, **M** by memory, **1**
show each core, **k** kill a PID, **q** quit. The header repeats the load average, and the `%wa`
value shows CPU time spent waiting for disks. `htop` is a friendlier version if it's installed,
and `watch -n 2 'ps aux --sort=-%cpu | head'` gives you a simple live view of anything.

> **Figure.** A real top screen. The header shows uptime, a load average of 1.79, 4 tasks, CPU at 34.2% user and 49.1% system, and memory and swap totals. Below, sorted by CPU: gzip at 98% and yes at 93%, both in state R (running), while python3 and sleep are in state S (sleeping) at 0%.
>
> Two runaways at the top of the list, each using a whole core: exactly what the mission below asks you to find. top -p limited this view to four demo processes.

> **Video.** [Linux Crash Course - The ps Command](https://www.youtube.com/watch?v=wYwGNgsfN3I) (Learn Linux TV)

## Jobs: foreground, background and after logout

A foreground command owns the terminal until it finishes. That is convenient for short work, but an SSH
disconnect can send a hang-up signal to jobs associated with that shell. Bash job control lets you pause and
resume work in the background; `nohup`, `tmux` or a service manager handles work that must survive a logout.

```sh
$ ./long-task.sh                 # runs in the foreground: the prompt waits
^Z                               # Ctrl+Z pauses it
[1]+  Stopped                 ./long-task.sh
$ bg                             # continue it in the background
$ jobs                           # this shell's jobs
[1]+  Running                 ./long-task.sh &
$ fg %1                          # bring it back to the foreground
$ ./another-task.sh &            # & starts it in the background straight away
```

Jobs belong to your shell. When your SSH session ends, the shell sends them **SIGHUP** and they
stop. For anything that must outlive your session:

```sh
$ nohup ./backup.sh > backup.log 2>&1 &   # ignore the hang-up, log to a file
$ tmux new -s deploy                      # a session that lives on the server
                                          # Ctrl+B then D detaches; log out safely
$ tmux attach -t deploy                   # later, from any SSH login: reattach
```

Use `&` or `bg` for temporary work while you keep using the same shell. Use `tmux` when you need to detach and
reattach interactively. Use systemd for a long-running workload that should start on boot and be supervised.
Redirect output so it does not fill or disappear with the terminal. A common mistake is assuming `&` alone
makes a job survive SSH logout; it only puts the job in the background of that shell.

> **In production.** Start every long operation (migrations, backups, big copies) inside `tmux` or `screen`. A dropped Wi-Fi connection halfway through a database migration is a bad afternoon. For things that should always run, don't use either: make them a systemd service.

## Signals: asking and forcing

A **signal** is a message to a process. `kill` sends them, despite its name:

> **Figure.** The signals you'll use. SIGTERM, 15, is the default for kill: it asks the process to finish cleanly, and the program can save work and exit. SIGINT, 2, is Ctrl+C. SIGHUP, 1, makes many services reload their config. SIGKILL, 9, is sent to the kernel, not the program: the process is removed instantly, with no clean-up. Try SIGTERM, wait, and use SIGKILL only if it's still there.
>
> Ask first (TERM), force last (KILL). A killed process can't save its work.

```sh
$ kill 4821                 # SIGTERM (15): please stop, cleanly
$ kill -HUP 812             # SIGHUP (1): nginx re-reads its config
$ kill -9 4821              # SIGKILL: the kernel removes it at once. Last resort
$ pkill -f "python worker.py"   # by command line instead of PID
$ killall node              # every process with that exact name
$ kill -l                   # the full list
```

> **Figure.** Animated. kill 4821 sends SIGTERM: the worker finishes the current order, writes and closes its file, closes database connections and exits 0. kill -9 4822 sends SIGKILL while that worker is writing orders.db: the kernel removes it at once, the file is left half-written, connections drop mid-request and there is no clean-up.
>
> SIGTERM lets the program finish its work. SIGKILL stops it mid-sentence, whatever it was doing.

Always try `kill` (TERM) first, wait a few seconds, check with `ps -p 4821`, and only then
use `-9`. A database killed with `-9` may need recovery when it starts again.

A **zombie** (`Z`) is already dead, so you can't kill it. It's waiting for its parent to read its
exit status. One or two are harmless. Thousands mean the parent program has a bug: restart the
parent, and the zombies go with it.

> **Video.** [How to use the kill command in Linux (Linux Crash Course Series)](https://www.youtube.com/watch?v=5ER65GtElmo) (Learn Linux TV)

## Priorities: nice and renice

Linux schedules runnable processes onto CPU cores. A **nice** value influences the scheduling priority among
ordinary tasks: a higher nice value means the process is more willing to yield CPU to other work. New
processes normally start at 0; values range from -20 (highest priority) to 19 (lowest).

```sh
$ nice -n 15 tar czf backup.tar.gz /srv    # start a heavy job politely
$ renice -n 10 -p 4821                     # make a running process give way
4821 (process ID) old priority 0, new priority 10
$ sudo renice -n -5 -p 812                 # only root may raise priority
```

Use `nice` for backups, report jobs and big compressions on a server that's also serving users:
the job takes a little longer, and the users don't notice it.

Use a positive nice value for background batch work that should not compete aggressively with interactive
services. Raising priority requires extra privilege on many systems; lowering priority is usually allowed to
the process owner. Nice does not reserve CPU or fix memory and I/O bottlenecks. A common mistake is using
`renice` to respond to high load without first identifying which process is responsible.

> **Video.** [Linux Process Tuning Made Easy: Understanding nice and renice](https://www.youtube.com/watch?v=VjZKvkZQm1U) (Learn Linux TV)

## Mission: Stop a runaway process, gently

Someone left a process spinning at 100% CPU and users say the server is slow. Find it, make it give way to everything else while you investigate, then stop it cleanly and prove it's gone.

- You need: A busy process (you'll start one with yes)
- You'll have: No yes process left; the busiest-process list returns to normal

```sh
$ yes > /dev/null &                         # the "runaway" for this mission
[1] 4821
$ ps aux --sort=-%cpu | head -3             # 1. find it
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
rajeev      4821 99.6  0.0   8392  1792 pts/0    R    10:51   0:21 yes
$ renice -n 19 -p 4821                      # 2. calm it down while you look
4821 (process ID) old priority 0, new priority 19
$ ps -o pid,ppid,user,ni,cmd -p 4821        # 3. who started it, and from where?
    PID    PPID USER      NI CMD
   4821    2210 rajeev    19 yes
$ kill 4821                                 # 4. ask it to stop (SIGTERM)
$ pgrep yes || echo "gone"                  # 5. prove it
gone
```

The PPID (2210) tells you which shell started it, which is how you find the person or script
responsible. Here SIGTERM was enough. `kill -9` would only have been needed if `pgrep` still
found it after a few seconds.

## Try it

- Run `ps aux --sort=-%cpu | head -5` and name the busiest process.
- Open `top`, press `P` (sort by CPU), `M` (by memory), `1` (per core), then `q`.
- Start `sleep 300 &`, list it with `jobs`, bring it back with `fg`, pause it with Ctrl+Z, continue it with `bg`.
- Find the sleep with `pgrep -a sleep` and stop it with `kill` (SIGTERM).
- Run `pstree -p | head -20` and follow the tree from PID 1 to your shell.
- Run the mini mission, then check the process is gone with `pgrep yes`.

## Quiz

1. A process won't stop with kill 4821. What should you do first?
   - kill -9 4821 straight away
   - **Wait a few seconds and check: it may be shutting down cleanly; use kill -9 only if it's still there** (answer)
   - Reboot the server
   Why: kill sends SIGTERM, which asks the program to finish its work and exit. SIGKILL (-9) stops it instantly, with no chance to save data or close connections.

2. You start a long backup over SSH and your laptop goes to sleep. How could you have kept the backup running?
   - **Run it with nohup, or inside tmux or screen** (answer)
   - Run it with sudo
   - Press Ctrl+Z
   Why: When the SSH session ends, its processes get SIGHUP. nohup ignores that signal; tmux and screen keep a session on the server you can reattach to later.

3. What does a nice value of 19 mean?
   - Highest priority
   - **Lowest priority: the process gives way to everyone else** (answer)
   - The process has 19 threads
   Why: Nice goes from -20 (highest priority) to 19 (lowest), and new processes start at 0. Anyone can lower their own priority; raising it needs root.

4. Many services reload their config on one signal without restarting. Which one?
   - **SIGHUP (1)** (answer)
   - SIGKILL (9)
   - SIGSTOP (19)
   Why: Originally "the terminal hung up", SIGHUP is used by nginx, sshd and many daemons to mean "re-read your config". systemctl reload often sends exactly this.

5. What is PID 1 on a modern Linux server?
   - The kernel
   - **systemd (the init system), the ancestor of every other process** (answer)
   - The first user who logged in
   Why: The kernel starts PID 1, and every other process is forked from it or from its descendants. If PID 1 dies, the system goes down.

## Resources

- [ps(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/ps.1.html) (Ubuntu manpages)
- [top(1) manual](https://manpages.ubuntu.com/manpages/noble/man1/top.1.html) (Ubuntu manpages)
- [signal(7): the list of signals and what they do](https://manpages.ubuntu.com/manpages/noble/man7/signal.7.html) (Ubuntu manpages)
- [tmux getting started](https://github.com/tmux/tmux/wiki/Getting-Started) (tmux)
- [LPIC-1 exam 101, objectives 103.5 and 103.6](https://www.lpi.org/our-certifications/exam-101-objectives/) (Linux Professional Institute)
