Learn / Linux / Processes & System
Lesson 24 of 74

Signals and Job Control

How Linux tells processes to stop, reload or pause: what signals are, SIGTERM vs SIGKILL and why the order matters, SIGHUP reloads, Ctrl+C and Ctrl+Z, kill, pkill and killall, foreground and background jobs with &, jobs, bg and fg, nohup, disown and tmux, and how systemd, Docker and Kubernetes use signals.

25 min read Report a problem Hands-on lab included 6-question quiz

What is a signal?

A signal is a small notification the kernel delivers to a process. It carries no data, just a number that means something like "please stop", "your terminal closed" or "pause".

When a signal arrives, a process does one of three things:

  1. Default action: for most signals, terminate (some also dump core, some pause or are ignored).
  2. Catch it: run its own handler, for example save work and exit, or reload configuration.
  3. Ignore it.

Two signals are special: SIGKILL and SIGSTOP can't be caught or ignored. The kernel acts on them directly.

Who sends signals

You, with killkill -TERM 27
The keyboardCtrl+C → SIGINT · Ctrl+Z → SIGTSTP
systemd · Docker · Kubernetesstop = SIGTERM, then SIGKILL
The kernelclosed terminal → SIGHUP · bad memory access → SIGSEGV · child exit → SIGCHLD
signal
The processcatch · ignore · default action
SIGKILL / SIGSTOPhandled by the kernel, no choice

kill -l lists them all:

text
 1) SIGHUP	 2) SIGINT	 3) SIGQUIT	 4) SIGILL	 5) SIGTRAP
 6) SIGABRT	 7) SIGBUS	 8) SIGFPE	 9) SIGKILL	10) SIGUSR1
11) SIGSEGV	12) SIGUSR2	13) SIGPIPE	14) SIGALRM	15) SIGTERM
16) SIGSTKFLT	17) SIGCHLD	18) SIGCONT	19) SIGSTOP	20) SIGTSTP

(The first four rows; the rest are rarely used directly.)

The ones you'll actually use:

SignalNo.DefaultTypical use
SIGTERM15terminate"Please exit." Sent by kill, systemctl stop, docker stop
SIGKILL9terminate (uncatchable)last resort for stuck processes
SIGINT2terminateCtrl+C
SIGHUP1terminateterminal disconnected; daemons: reload config
SIGQUIT3terminate + core dumpCtrl+; some apps print diagnostics
SIGTSTP20stopCtrl+Z (catchable)
SIGSTOP19stop (uncatchable)pause any process
SIGCONT18continueresume a stopped process (bg, fg)
SIGUSR1/210/12terminateapp-defined: e.g. reopen log files, dump stats
SIGCHLD17ignore"your child exited" (the parent should wait())
SIGSEGV11core dumpthe program accessed invalid memory: a crash

Sending signals: kill, pkill, killall

bash
kill 27              # SIGTERM to PID 27
kill -TERM 27        # same, by name
kill -15 27          # same, by number
kill -HUP 28         # reload
kill -9 29           # SIGKILL
kill -0 28           # send nothing: just check the PID exists and you may signal it
pkill -x shop-api    # by exact process name
pkill -u rohan       # every process of a user
killall nginx        # all processes with this exact name

Normal users can only signal their own processes; root can signal anything. pkill and killall match names, so always check with pgrep what a pattern matches before you send anything. pkill sh matches bash, sshd and flush.

SIGTERM first, SIGKILL last

bash
kill $(pgrep -x report-gen)
cat /var/log/report-gen.log
text
report generator started
received SIGTERM: saving partial report to /var/tmp/report.partial... stopped cleanly

The program caught SIGTERM and shut down properly: it saved its partial work. A database would finish its transactions and flush to disk; a web server would finish in-flight requests.

SIGKILL gives no such chance. The kernel simply removes the process, so:

  • files being written are left half-written,
  • lock files and PID files stay behind ("another instance is already running"),
  • temporary files aren't cleaned up,
  • clients see connections reset instead of closed.

The standard procedure is SIGTERM, wait, check, and only then SIGKILL:

text
kill 1234              # ask
sleep 10               # give it time
kill -0 1234 && kill -9 1234    # still there? force it

Every orchestrator automates exactly this:

ToolSendsThen, after
systemctl stopSIGTERMSIGKILL after TimeoutStopSec (90 s default)
docker stopSIGTERMSIGKILL after 10 s (-t to change)
Kubernetes pod deleteSIGTERMSIGKILL after terminationGracePeriodSeconds (30 s)

That's why apps in containers must handle SIGTERM: one that ignores it is always killed hard, after a pointless wait.

When SIGTERM doesn't work, /proc/PID/status tells you why:

text
SigIgn:	0000000001005006
SigCgt:	0000000000000000

SigIgn is a hex bitmask of ignored signals: bit n−1 stands for signal n. 0x4000 (bit 14) is signal 15, SIGTERM. This process ignores it deliberately, so only kill -9 will remove it.

Try it · Task 1 of 4

Stop gracefully

Stop the report generator so it saves its partial report first.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

The polite way to stop a program is SIGTERM, which is what kill PID sends by default. A well-written program catches it, finishes or saves what it's doing, closes files and connections cleanly, and exits. systemctl stop, docker stop and Kubernetes all send SIGTERM first for exactly this reason.

1. Find it

bash
pgrep -l -x 'report-gen|shop-api|stuck-export'

-x = exact name; the | lets one pattern match three names.

text
27 report-gen
28 shop-api
29 stuck-export

2. Send SIGTERM

bash
kill $(pgrep -x report-gen)
pgrep report-gen || echo "report-gen is gone"
cat /var/log/report-gen.log
CommandSame as
kill 27kill -15 27, kill -TERM 27, kill -SIGTERM 27
text
report-gen is gone
report generator started
received SIGTERM: saving partial report to /var/tmp/report.partial... stopped cleanly

The program caught SIGTERM, saved its partial report and exited on its own. Nothing was lost.

2 · Your task

Stop report-gen with SIGTERM (not SIGKILL) so it saves its work.

Expected result: report-gen is no longer running, /var/log/report-gen.log ends with "stopped cleanly", and /var/tmp/report.partial exists.

Hint: the commands, explained
text
kill $(pgrep -x report-gen)

What each part does

  • pgrep -x report-gen: the PID of the process named exactly report-gen.
  • kill PID: sends SIGTERM (15), asking the process to stop cleanly so it can finish writing and close files.
First start the lab machine in the terminal panel on the right.
Try it · Task 2 of 4

The last resort

Get rid of an export job that ignores normal requests to stop.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Sometimes a process is stuck, or deliberately ignores SIGTERM. SIGKILL (9) can't be caught or ignored: the kernel removes the process immediately. The price: it gets no chance to save data, finish writes, delete temporary files or release locks. That's why it's the last resort, never the first move.

1. Ask politely first

bash
kill $(pgrep stuck-export)
sleep 2
ps -o pid,stat,comm -p $(pgrep stuck-export)
text
    PID STAT COMMAND
     29 Ss   stuck-export

Still there after two seconds.

2. Why? Check its signal masks

bash
grep -E 'SigIgn|SigCgt' /proc/$(pgrep stuck-export)/status
text
SigIgn:	0000000001005006
SigCgt:	0000000000000000

SigIgn is a bitmask of ignored signals (SigCgt: caught). In hex, bit n−1 stands for signal n. The value ...1005006 includes bit 14 (0x4000 → signal 15, SIGTERM) and bit 1 (0x2 → signal 2, SIGINT). It ignores both on purpose. You won't decode these every day, but it's a real way to find out why a process won't stop.

3. Force it

bash
kill -9 $(pgrep stuck-export)
pgrep stuck-export || echo "stuck-export is gone"
text
stuck-export is gone

The professional order: kill PID (SIGTERM), wait 10–30 seconds, check again, and only then kill -9 PID. That's exactly what systemctl stop and docker stop do automatically (Docker waits 10 seconds by default).

2 · Your task

Get rid of stuck-export. Try SIGTERM first, then use SIGKILL.

Expected result: pgrep stuck-export prints nothing.

Hint: the commands, explained
text
kill $(pgrep stuck-export)
kill -9 $(pgrep stuck-export)

What each part does

  • First try kill (SIGTERM). This process ignores it, so ps still shows it running.
  • kill -9: SIGKILL. A process can't catch or ignore it; the kernel removes it immediately. Use it only after TERM fails, because the process gets no chance to clean up.
First start the lab machine in the terminal panel on the right.

SIGHUP: reload without downtime

Originally SIGHUP meant "the terminal hung up" (a modem disconnected). Daemons have no terminal, so most reuse it as "re-read your configuration":

bash
sed -i 's/^workers=.*/workers=8/' /etc/shop/api.conf
kill -HUP $(cat /run/shop-api.pid)
cat /var/log/shop-api.log
pgrep shop-api
text
config loaded: workers=2 log_level=info
config loaded: workers=8 log_level=info
28

New setting, same PID 28: no restart, no dropped connections. systemctl reload nginx does exactly this, and nginx -s reload is a friendly wrapper around it.

Only do this for programs documented to reload on SIGHUP. For anything else, SIGHUP's default action is to terminate.

Try it · Task 3 of 4

Reload without restarting

Change the API server's worker count and apply it without restarting the process.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Restarting a server to change one setting drops every connection in flight. Many daemons (nginx, sshd, rsyslog, haproxy, PostgreSQL) instead treat SIGHUP as "re-read your configuration": same process, same PID, new settings. systemctl reload usually just sends SIGHUP for you.

1. Current state

bash
cat /var/log/shop-api.log
cat /run/shop-api.pid

Daemons often write their PID into a PID file in /run, so scripts can signal them without searching.

text
config loaded: workers=2 log_level=info
28

2. Change the config and send SIGHUP

bash
sed -i 's/^workers=.*/workers=8/' /etc/shop/api.conf
kill -HUP $(cat /run/shop-api.pid)
cat /var/log/shop-api.log
pgrep shop-api
text
config loaded: workers=2 log_level=info
config loaded: workers=8 log_level=info
28

The server loaded the new value, and the PID is still 28: it never stopped.

Only send SIGHUP to programs documented to reload on it. For a program that doesn't catch it, the default action of SIGHUP is to terminate: the same signal your shell sends to its jobs when your SSH connection drops.

2 · Your task

Set workers=8 in /etc/shop/api.conf and make shop-api load it without restarting it.

Expected result: the log's last line shows workers=8, and shop-api still has the same PID as in /run/shop-api.pid before.

Hint: the commands, explained
text
sed -i 's/^workers=.*/workers=8/' /etc/shop/api.conf
kill -HUP $(cat /run/shop-api.pid)

What each part does

  • sed -i 's/^workers=.*/workers=8/': change the setting in the config file.
  • cat /run/shop-api.pid: the service wrote its PID here when it started.
  • kill -HUP PID: send SIGHUP. This service is written to reload its config on HUP, so it picks up workers=8 without restarting.
First start the lab machine in the terminal panel on the right.

Jobs: foreground and background

Your shell runs commands in the foreground: it waits until they finish. Put & at the end and the command becomes a background job: the shell prints its job number and PID and gives you the prompt back immediately.

This is a real session (^Z is Ctrl+Z, ^C is Ctrl+C):

text
root@devopsshack:~# sleep 500
^Z
[1]+  Stopped                 sleep 500
root@devopsshack:~# jobs -l
[1]+     7 Stopped                 sleep 500
root@devopsshack:~# bg
[1]+ sleep 500 &
root@devopsshack:~# sleep 600 &
[2] 8
root@devopsshack:~# jobs
[1]-  Running                 sleep 500 &
[2]+  Running                 sleep 600 &
root@devopsshack:~# fg %2
sleep 600
^C
root@devopsshack:~# kill %1
root@devopsshack:~# jobs
[1]+  Terminated              sleep 500

Job states and how to move between them

Foregroundhas your keyboard
Ctrl+Z
Stoppedpaused, uses no CPU
bg
Backgroundrunning, you keep typing

fg brings a stopped or background job back to the foreground. Ctrl+C interrupts the foreground job. kill %N signals a job by number.

CommandDoes
cmd &start in the background
jobs / jobs -llist this shell's jobs (with PIDs)
Ctrl+Zpause the foreground job
bg [%N]resume a job in the background
fg [%N]bring a job to the foreground
kill %Nsignal a job by job number
$!PID of the last background job
waitwait for all background jobs (useful in scripts)

Jobs belong to one shell. Another terminal's jobs won't show them; use ps and pgrep there.

A background job that tries to read from the keyboard gets stopped automatically (Stopped (tty input)), and one that writes still prints into your terminal. Redirect its output to a file to keep your screen clean.

Surviving logout

When your terminal closes (you log out, or SSH drops), the shell sends SIGHUP to its jobs, and they die. Four ways to keep something running:

bash
nohup /opt/jobs/backup.sh > /root/backup.log 2>&1 &   # immune to SIGHUP from the start
disown %1                                             # detach an already-running job from the shell
tmux new -s backup                                    # a terminal session that survives disconnects
text
backup started at 16:10:59
copied chunk 1
copied chunk 2
70 /bin/bash /opt/jobs/backup.sh

The backup's log and process after nohup ... &. Without the redirect, nohup writes output to nohup.out. In a real terminal it also prints nohup: ignoring input when it starts.

UseFor
nohup cmd > log 2>&1 &a one-off long command
disownyou forgot nohup and the job is already running
tmux / screeninteractive work you want to reattach to later
systemd serviceanything that must run reliably: restarts, boot start, logging, limits

kill -9 as the default. It works every time, and it's how databases get corrupted and lock files get left behind. SIGTERM first.

killall or pkill with a loose pattern. On Solaris, killall kills everything. On Linux, a short pattern matches more than you think. Run pgrep -l pattern first.

Long jobs with & over SSH. They die when the connection drops. Use nohup, tmux or a service.

Restarting to apply config. If the daemon supports reload (systemctl reload, SIGHUP), use it: no dropped connections.

"What's the difference between kill and kill -9?" kill sends SIGTERM, which the process can catch to shut down cleanly. kill -9 sends SIGKILL, which can't be caught: instant termination with no cleanup.

"A process won't die with kill -9. Why?" It's a zombie (already dead; fix the parent) or in D state, stuck in the kernel on I/O; it dies when the I/O returns.

"How do you reload nginx without dropping connections?" systemctl reload nginx or nginx -s reload, which send SIGHUP.

"How does Kubernetes stop a pod?" SIGTERM to the containers, waits terminationGracePeriodSeconds (30 s default), then SIGKILL. Apps should handle SIGTERM.

"How do you keep a command running after you log out?" nohup, disown, tmux/screen, or (properly) a systemd service.

Try it · Task 4 of 4

Background jobs

Run the long backup in the background so it keeps going after you log out.

1 · See how it's done Read this, then run the commands in your terminal (or press ▶ Run)

Your shell runs one command in the foreground at a time and waits for it. Add & and the command runs in the background while you keep typing. The shell calls these jobs and numbers them %1, %2... But background jobs still belong to your terminal: when you log out, the shell sends them SIGHUP and they die. nohup makes a command ignore SIGHUP so it survives.

1. Job control in action

This is a real terminal session (Ctrl+Z shows as ^Z, Ctrl+C as ^C):

text
root@devopsshack:~# sleep 500
^Z
[1]+  Stopped                 sleep 500
root@devopsshack:~# jobs -l
[1]+     7 Stopped                 sleep 500
root@devopsshack:~# bg
[1]+ sleep 500 &
root@devopsshack:~# jobs
[1]+  Running                 sleep 500 &
root@devopsshack:~# sleep 600 &
[2] 8
root@devopsshack:~# jobs
[1]-  Running                 sleep 500 &
[2]+  Running                 sleep 600 &
root@devopsshack:~# fg %2
sleep 600
^C
root@devopsshack:~# jobs
[1]+  Running                 sleep 500 &
root@devopsshack:~# kill %1
root@devopsshack:~# jobs
[1]+  Terminated              sleep 500
ActionWhat happened
Ctrl+Zpaused the foreground command (SIGTSTP): Stopped
jobs -llisted jobs with their PIDs
bgcontinued the stopped job in the background (SIGCONT)
cmd &started a job directly in the background; [2] 8 = job 2, PID 8
fg %2brought job 2 to the foreground
Ctrl+Cinterrupted it (SIGINT)
kill %1sent SIGTERM to job 1, by job number instead of PID

+ marks the "current" job (the default for fg and bg), - the previous one. Try it yourself in the terminal.

2. Surviving logout with nohup

bash
nohup /opt/jobs/backup.sh > /root/backup.log 2>&1 &
sleep 3
cat /root/backup.log
pgrep -af backup.sh
PartMeaning
nohuprun the command immune to SIGHUP
> /root/backup.log 2>&1send output and errors to a file (otherwise nohup writes nohup.out)
&in the background
text
backup started at 16:10:59
copied chunk 1
copied chunk 2
70 /bin/bash /opt/jobs/backup.sh

In a real terminal the log starts with one extra line, nohup: ignoring input: nohup telling you it detached the job from your keyboard. You can log out now and the backup keeps going. Follow it later with tail -f /root/backup.log.

For anything that must run reliably (restart on crash, start at boot, logs, limits), don't use nohup: make it a systemd service (Writing systemd Services lesson). For interactive work you want to come back to, use tmux or screen. nohup is for one-off long jobs.

2 · Your task

Start /opt/jobs/backup.sh in the background with nohup, writing its output and errors to /root/backup.log.

Expected result: pgrep -f backup.sh shows it running, and /root/backup.log starts with "backup started".

Hint: the commands, explained
text
nohup /opt/jobs/backup.sh > /root/backup.log 2>&1 &

What each part does

  • nohup: make the script ignore SIGHUP, the signal sent when your terminal closes, so it keeps running after you log out.
  • > /root/backup.log 2>&1: all output and errors go to the log. &: run it in the background.
First start the lab machine in the terminal panel on the right.

Summary

  • Signals are numbered notifications. Processes catch, ignore or take the default action; SIGKILL and SIGSTOP can't be caught.
  • kill = SIGTERM (polite stop). kill -HUP = reload for most daemons. kill -9 = SIGKILL, last resort.
  • SIGTERM, wait, then SIGKILL: what systemd, Docker and Kubernetes all do.
  • pkill, killall by name; check with pgrep first.
  • Jobs: &, jobs, Ctrl+Z, bg, fg, kill %N.
  • Logout sends SIGHUP: use nohup, disown, tmux, or a systemd service.
Check your understanding

Quick quiz

Feedback