# Create, monitor and kill processes

> Foreground and background jobs, nohup, screen and tmux, ps, top, free, uptime and watch, and signals with kill, pkill and killall.

Source: https://aminbytes.dev/bytes/gnu-and-unix-commands/processes/


Every command you run becomes a **process**: a running program with its own memory, its own owner and a number called a **PID** (process ID). A server runs hundreds of them at once. As an admin you need to start them the right way, see what they're doing, and stop the ones that misbehave.

This byte covers jobs in the foreground and background, keeping programs alive after you log out, watching processes and memory, and sending signals.

## Foreground and background jobs

When you run a command normally, it runs in the **foreground**: the shell waits until it finishes, and you can't type anything else. Add `&` at the end to run it in the **background** instead:

```bash
sleep 600 &
```

```text
[1] 2481
```

The shell prints a **job number** in brackets and the PID. The prompt comes back right away. The PID of the last background job is in `$!`.

A **job** is a command started from *this* shell. `jobs` lists them:

```bash
sleep 700 &
jobs
jobs -l
```

```text
[1]-  Running                 sleep 600 &
[2]+  Running                 sleep 700 &
[1]-   2481 Running                 sleep 600 &
[2]+   2490 Running                 sleep 700 &
```

`+` marks the current job (the one `fg` and `bg` use by default), `-` the one before it. `jobs -l` adds the PIDs.

### Moving jobs around

| Action | How |
| --- | --- |
| Stop (pause) the foreground job | `Ctrl+Z` |
| Interrupt (end) the foreground job | `Ctrl+C` |
| Resume a stopped job in the background | `bg` or `bg %1` |
| Bring a job to the foreground | `fg` or `fg %2` |
| Kill a job by its number | `kill %1` |

```console
$ tar -czf backup.tar.gz /home
^Z
[1]+  Stopped                 tar -czf backup.tar.gz /home
$ bg
[1]+ tar -czf backup.tar.gz /home &
$ fg %1
tar -czf backup.tar.gz /home
```

Job numbers start with `%`: `%1` is job 1, `%+` (or `%%`) the current job, `%-` the previous one, and `%tar` the job whose command starts with `tar`. Without the `%`, `kill 1` would mean PID 1, which is `init` or `systemd`.

## Keeping programs running after logout

When you close a terminal or your SSH connection drops, the shell sends **SIGHUP** (hang up) to its jobs, and most programs exit. There are several ways around that.

### nohup

`nohup` starts a command that ignores SIGHUP. If the output would go to the terminal, it's written to `nohup.out` instead:

```bash
nohup ./long-import.sh &
```

```text
nohup: ignoring input and appending output to 'nohup.out'
```

`nohup.out` is created in the current directory (or in your home directory if that's not writable). Better to choose the file yourself: `nohup ./long-import.sh > import.log 2>&1 &`.

 (Side note: Forgot `nohup`? The Bash builtin `disown` removes a running job from the shell's job list, so the shell won't send it SIGHUP when you log out: start it, press `Ctrl+Z`, type `bg`, then `disown %1`.)

### screen and tmux

A **terminal multiplexer** runs a shell session on the server that keeps going when you disconnect. You **detach** from it, log out, log in again later (even from another computer) and **attach** to find everything just as you left it. It can also hold several windows in one terminal.

`screen` is the classic one, `tmux` the modern one. RHEL 8 and later ship only `tmux`; `screen` comes from EPEL there. On Debian and Ubuntu both are a package install away.

| Task | screen | tmux |
| --- | --- | --- |
| Start a named session | `screen -S work` | `tmux new -s work` |
| Detach | `Ctrl+A` then `d` | `Ctrl+B` then `d` |
| List sessions | `screen -ls` | `tmux ls` |
| Reattach | `screen -r work` | `tmux attach -t work` |
| New window | `Ctrl+A` then `c` | `Ctrl+B` then `c` |
| Next window | `Ctrl+A` then `n` | `Ctrl+B` then `n` |
| Split the screen | `Ctrl+A` then `S` | `Ctrl+B` then `%` or `"` |
| End the session | `exit` in every window | `exit` in every window |

```console
$ screen -ls
There is a screen on:
	3761.work	(12/01/26 12:17:09)	(Detached)
1 Socket in /run/screen/S-amin.
$ tmux ls
web: 1 windows (created Tue Dec  1 12:17:09 2026)
```

> [!TIP]
> Start a `tmux` or `screen` session *before* any long job over SSH, like a big upgrade. If the connection drops halfway, the upgrade keeps running and you just reattach.

## Watching processes: ps

`ps` takes a snapshot of the running processes. Without options it shows only the ones in your current terminal:

```bash
ps
```

```text
    PID TTY          TIME CMD
   2210 pts/0    00:00:00 bash
   2533 pts/0    00:00:00 ps
```

`ps` accepts two option styles, which is confusing at first. **BSD style** has no dash, **UNIX style** has one. The two you'll use most:

```bash
ps aux        # BSD style: all processes, user-oriented format
ps -ef        # UNIX style: every process, full format
```

```text
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.3 168232 13180 ?        Ss   Nov28   0:09 /sbin/init
root         612  0.0  0.2  15432  9020 ?        Ss   Nov28   0:00 sshd: /usr/sbin/sshd -D
amin        2481  0.0  0.0   5480  1020 pts/0    S    12:17   0:00 sleep 600

UID          PID    PPID  C STIME TTY          TIME CMD
root           1       0  0 Nov28 ?        00:00:09 /sbin/init
root         612       1  0 Nov28 ?        00:00:00 sshd: /usr/sbin/sshd -D
amin        2481    2210  0 12:17 pts/0    00:00:00 sleep 600
```

`ps aux` shows CPU and memory use; `ps -ef` shows the **PPID** (parent process ID), so you can see who started what. `VSZ` is virtual memory and `RSS` the real memory in use, both in KiB.

### Selecting and sorting

| Command | Shows |
| --- | --- |
| `ps -u amin` | Processes of one user |
| `ps -p 612` | One PID |
| `ps -C sshd` | Processes with this command name |
| `ps -ef --forest` or `ps axjf` | The parent/child tree |
| `ps -eo pid,user,%cpu,%mem,cmd` | Only the columns you name |
| `ps aux --sort=-%mem` | Sorted by memory, biggest first (`-` means descending) |

```bash
ps -eo pid,user,%mem,cmd --sort=-%mem | head -4
```

```text
    PID USER     %MEM CMD
   1340 mysql     9.8 /usr/sbin/mariadbd
    988 www-data  2.1 php-fpm: pool www
    987 www-data  2.0 php-fpm: pool www
```

### Process states

The `STAT` column tells you what a process is doing:

| Code | State |
| --- | --- |
| `R` | Running, or ready to run |
| `S` | Sleeping, waiting for something (most processes) |
| `D` | Uninterruptible sleep, usually waiting for disk or network I/O |
| `T` | Stopped (for example with `Ctrl+Z`) |
| `Z` | Zombie: finished, but the parent hasn't collected its exit status yet |

Extra letters add detail: `s` session leader, `+` in the foreground, `<` high priority, `N` low priority, `l` multi-threaded.

### pgrep

`pgrep` finds PIDs by name, which beats `ps aux | grep` (that also finds the `grep` itself):

```bash
pgrep sshd
pgrep -l sleep
pgrep -a sleep
pgrep -u amin -c bash
```

```text
612
2481 sleep
2481 sleep 600
1
```

`-l` adds the name, `-a` the full command line, `-u` filters by user, `-c` counts, and `-f` matches against the full command line instead of just the name.

## Watching live: top

`top` shows processes live, refreshing every few seconds, with the busiest at the top:

```text
top - 12:17:09 up 3 days,  2:41,  2 users,  load average: 0.31, 0.24, 0.20
Tasks: 142 total,   1 running, 141 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.3 us,  0.7 sy,  0.0 ni, 96.8 id,  0.2 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :   3915.2 total,    512.4 free,   1650.7 used,   1752.1 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   2010.3 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
   1340 mysql     20   0 1785204 392816  23040 S   1.7   9.8  12:04.33 mariadbd
    988 www-data  20   0  245612  84300  61200 S   0.3   2.1   0:41.10 php-fpm8.2
```

The header holds the same numbers as `uptime` and `free`. In the CPU line, `us` is user programs, `sy` the kernel, `ni` niced processes, `id` idle and `wa` waiting for I/O.

| Key | Action |
| --- | --- |
| `P` / `M` / `T` | Sort by CPU / memory / running time |
| `k` | Kill: asks for a PID and a signal |
| `r` | Renice: change a process's priority |
| `u` | Show only one user's processes |
| `1` | Show each CPU separately |
| `c` | Show full command lines |
| `h` | Help |
| `q` | Quit |

Useful options: `top -d 5` refreshes every 5 seconds, `top -u amin` shows one user, `top -p 1340` shows one PID, and `top -b -n 1` prints one snapshot as plain text (batch mode), which you can save or pipe.

 (Side note: `htop` is a friendlier version of `top`, with colors, mouse support and scrolling. It isn't on the exam and isn't always installed, so learn `top` first.)

## Memory and load: free and uptime

`free` shows memory and swap:

```bash
free -h
```

```text
               total        used        free      shared  buff/cache   available
Mem:           3.8Gi       1.6Gi       512Mi        24Mi       1.7Gi       2.0Gi
Swap:          2.0Gi          0B       2.0Gi
```

`-h` gives human units (`-m` MiB, `-g` GiB). Don't panic about a small `free` number: Linux uses spare memory as a disk cache (`buff/cache`) and gives it back when programs need it. The column that matters is **available**. `free -s 5` repeats every 5 seconds.

`uptime` shows the time, how long the system has run, how many users are logged in and the **load average**:

```bash
uptime
```

```text
 12:17:08 up 3 days,  2:41,  2 users,  load average: 0.31, 0.24, 0.20
```

The load average is the average number of processes that are running or waiting to run (or stuck waiting for disk) over the last 1, 5 and 15 minutes. Compare it with your CPU count (`nproc`): a load of 4.0 on 4 cores means fully busy, on 1 core it means a long queue. `uptime -p` prints just the "up 3 days, 2 hours" part. The same numbers are in `/proc/loadavg`.

## Repeating a command: watch

`watch` runs a command over and over (every 2 seconds by default) and shows the output full screen, so you can see changes happen:

```bash
watch free -h
watch -n 5 'ps aux --sort=-%cpu | head'
watch -d ls -l /var/spool/cups
```

`-n` sets the interval in seconds and `-d` highlights what changed since the last run. Quote commands that contain pipes. `Ctrl+C` exits.

## Signals: kill, pkill and killall

You don't really "kill" a process: you send it a **signal**, a small message from the kernel. The process can react to most signals, for example by cleaning up and exiting. `kill -l` lists them all; these are the ones to know:

| Number | Name | Meaning | Can be caught? |
| --- | --- | --- | --- |
| 1 | `SIGHUP` | Hang up: terminal closed. Many daemons reload their config on it | Yes |
| 2 | `SIGINT` | Interrupt, what `Ctrl+C` sends | Yes |
| 3 | `SIGQUIT` | Quit and dump core (`Ctrl+\`) | Yes |
| 9 | `SIGKILL` | Kill immediately, no cleanup | **No** |
| 15 | `SIGTERM` | Please terminate. The default of `kill` | Yes |
| 18 | `SIGCONT` | Continue a stopped process | Yes, but it always resumes |
| 19 | `SIGSTOP` | Stop (pause) the process | **No** |
| 20 | `SIGTSTP` | Stop from the terminal, what `Ctrl+Z` sends | Yes |

### kill

`kill` sends a signal to one or more PIDs (or `%jobs`). All these forms send signal 9:

```bash
kill 2481              # SIGTERM (15), the polite way
kill -9 2481
kill -KILL 2481
kill -SIGKILL 2481
kill -s KILL 2481
kill -HUP 612          # ask sshd to reload its config
```

Always try `SIGTERM` first and give the program a few seconds. `SIGKILL` stops it instantly, but it can't save files, remove lock files or close connections cleanly.

`kill -l 15` turns a number into a name (`TERM`), and `kill -l TERM` does the reverse.

### pkill and killall

These send signals by **name** instead of PID:

```bash
pkill sleep            # every process whose name matches "sleep" (a pattern)
pkill -u amin firefox  # only amin's processes
pkill -f "python3 worker.py"   # match the full command line
killall sleep          # every process named exactly "sleep"
killall -HUP rsyslogd
```

Both send `SIGTERM` by default and accept the same signal options as `kill`. The difference: `pkill` matches a **pattern** (so `pkill ssh` also hits `sshd` and `ssh-agent`), while `killall` wants the **exact** process name. `pgrep` and `pkill` take the same options, so test with `pgrep -a` first to see what you'd hit.

`pgrep` and `pkill` come from the `procps` package (`procps-ng` on RHEL and Fedora). `killall` comes from `psmisc`, which minimal systems sometimes leave out.

> [!WARNING]
> On some old UNIX systems like Solaris, `killall` really kills *all* processes. On Linux it's safe, but don't type it from habit on unfamiliar systems.

## Exam checklist

- `cmd &` runs in the background. `Ctrl+Z` stops a job, `bg` resumes it in the background, `fg` brings it back. `jobs -l` lists jobs with PIDs. Jobs are `%1`, `%+`, `%-`.
- `nohup cmd &` survives logout (ignores SIGHUP); output goes to `nohup.out`. `screen` (`Ctrl+A d`, `screen -r`) and `tmux` (`Ctrl+B d`, `tmux attach`) keep whole sessions alive.
- `ps aux` (BSD style) and `ps -ef` (UNIX style) list all processes. `-u` user, `-p` PID, `-C` name, `-o` columns, `--sort=-%mem`, `--forest`.
- States: `R` running, `S` sleeping, `D` waiting for I/O, `T` stopped, `Z` zombie.
- `top` keys: `P` CPU, `M` memory, `k` kill, `r` renice, `q` quit. `top -b -n 1` for a snapshot.
- `free -h`: look at **available**, not free. `uptime`: load average over 1, 5 and 15 minutes.
- `watch -n 5 cmd` reruns a command every 5 seconds (default 2), `-d` highlights changes.
- Signals: 1 HUP, 2 INT (`Ctrl+C`), 9 KILL, 15 TERM (default), 18 CONT, 19 STOP, 20 TSTP (`Ctrl+Z`). 9 and 19 can't be caught.
- `kill` uses PIDs, `pkill` matches a name pattern, `killall` an exact name. `pgrep` finds PIDs the same way `pkill` would.


## Byte check

1. A program ignores `kill 1234`. Which signal ends it without giving it a chance to refuse?
   - `SIGHUP` (1)
   - **`SIGKILL` (9)** (correct)
   - `SIGTERM` (15)
   `kill` sends `SIGTERM` (15) by default, which a program may catch or ignore. `SIGKILL` (9) is handled by the kernel and can't be caught, so the process can't clean up either.

2. You pressed `Ctrl+Z` on a long `rsync`. How do you let it keep running while you use the shell?
   - `fg`
   - **`bg`** (correct)
   - `nohup`
   `Ctrl+Z` stops the job. `bg` resumes it in the background; `fg` would resume it in the foreground and take the terminal again.

3. What do the three numbers after `load average:` in `uptime` mean?
   - CPU use in percent for user, system and idle
   - **The average number of runnable or waiting processes over 1, 5 and 15 minutes** (correct)
   - Memory, swap and disk usage
   Load average counts processes that are running or waiting to run (or waiting for disk). Compare it to the number of CPUs: a load of 4 on a 4-core machine means fully busy.


