Skip to content
KALANBLON
Show contents

Chapter 1 of 7 · 20 min

Processes and signals

By the end of this chapter, you'll be able to

  • Describe a process: PID, parent, state, exit status
  • Start a process in the background and wait for it with wait
  • Send a signal with kill and tell SIGTERM from SIGKILL
  • Catch a signal with trap to stop a script cleanly

A process is a running program

A process is a program that is running. Linux gives it a unique number, the PID (process identifier), and records its parent: the process that started it. When you type a command in a terminal, the shell (Bash) creates a child process to run it.

$ ps -o pid,ppid,stat,comm
    PID    PPID STAT COMMAND
   2817    2810 Ss   bash
   3104    2817 R+   ps
  • PID: the process number;
  • PPID: its parent's number (here, ps is the child of bash);
  • STAT: its state (R: running, S: sleeping while waiting for an event, Z: finished but not yet "collected" by its parent, a zombie).

Linux also exposes each process as a folder in /proc. The file /proc/<PID>/status describes the process; $$ holds the PID of the current shell:

grep "^Name" /proc/$$/status
echo "(it really is the shell running this block)"
Name:	bash
(it really is the shell running this block)

Foreground, background and exit status

A command followed by & runs in the background: the shell does not wait for it to finish. $! holds the PID of the last process started this way, and wait PID waits for it to end and collects its exit status (0: success, anything else: failure).

(sleep 0.2; exit 3) &
pid=$!
echo "started in the background"
code=0
wait "$pid" || code=$?
echo "finished with status $code"
started in the background
finished with status 3

We write wait "$pid" || code=$? because the course examples run in strict mode (set -e): a non-zero status would stop the script, when we only want to read it.

Signals: talking to a process

A signal is a short message that the kernel delivers to a process. The most useful ones in administration:

SignalNumberDefault effectCan the process react?
SIGTERM15stopyes: this is the polite request
SIGINT2stop (Ctrl + C)yes
SIGHUP1stop; many services use it to reload their configurationyes
SIGKILL9immediate stop by the kernelno: no cleanup, no saving

kill sends a signal (SIGTERM by default): its name sounds scary, but it is used to send any signal. When a process dies because of a signal, its exit status is 128 + the signal number: 143 for SIGTERM, 137 for SIGKILL.

sleep 30 &
pid=$!
kill -0 "$pid" && echo "the process is running"
kill -TERM "$pid"
code=0
wait "$pid" 2>/dev/null || code=$?
echo "exit status: $code (128 + 15)"
the process is running
exit status: 143 (128 + 15)

kill -0 sends no signal: it only checks that the process exists and that you are allowed to talk to it. The 2>/dev/null after wait hides the "Terminated" message that Bash prints when a job dies from a signal.

Catching a signal with trap

A script can catch a signal with trap and run some code before stopping: close a file, delete a temporary file, send a warning. Here is a small "service" that stops cleanly when it receives SIGTERM:

cat > service.sh <<'EOF'
trap 'echo "SIGTERM received: closing the file, clean stop"; exit 0' TERM
echo "service started"
while true; do sleep 0.1; done
EOF

bash service.sh &
pid=$!
sleep 0.5
kill -TERM "$pid"
code=0
wait "$pid" || code=$?
echo "exit status: $code"
service started
SIGTERM received: closing the file, clean stop
exit status: 0

The EXIT pseudo-signal is even handier: its code runs at every end of the script, normal or on error.

tmp=report.tmp
echo "draft" > "$tmp"
trap 'rm -f "$tmp"; echo "temporary file deleted"' EXIT
echo "working with $tmp"
working with report.tmp
temporary file deleted

Only if the service no longer responds: the kernel stops it without giving it time to clean up.

Step 4 of 4
Text description of the animation
  1. The administrator asks the service to stop.
  2. The service has a trap: it runs its cleanup code.
  3. The service stops by itself, cleanly. Nothing is lost.
  4. Only if the service no longer responds: the kernel stops it without giving it time to clean up.

Your turn

Worked exercise

Worked exercise: watching three tasks

Start three tasks in the background: the first succeeds after 0.1 seconds, the second fails with status 2, the third succeeds after 0.3 seconds. Wait for all of them, print each one's status, then the number of failed tasks.

Hint 1
Store each $! in an array: pids+=("$!").
Hint 2
Loop over the array with for pid in "${pids[@]}", and collect each status with wait "$pid" || code=$? (resetting code=0 before each wait).
Show the solution and common mistakes
pids=()
(sleep 0.1; exit 0) & pids+=("$!")
(exit 2) & pids+=("$!")
(sleep 0.3; exit 0) & pids+=("$!")

failures=0
number=1
for pid in "${pids[@]}"; do
  code=0
  wait "$pid" || code=$?
  echo "task $number: status $code"
  if [ "$code" -ne 0 ]; then failures=$((failures + 1)); fi
  number=$((number + 1))
done
echo "$failures task(s) failed"
task 1: status 0
task 2: status 2
task 3: status 0
1 task(s) failed

Common mistakes:

  • Calling wait with no argument: it waits for all tasks, but does not give each one's status.
  • Reading $? after another command (an echo, for example): $? only keeps the status of the last command.
  • Forgetting || code=$? in strict mode: the first non-zero status stops the whole script.

Summary

  1. 1A process has a PID, a parent and a state; /proc/PID/ describes it.
  2. 2& runs in the background, $! gives the PID, wait PID waits for the end and returns the exit status.
  3. 3kill sends a signal: SIGTERM (15) asks for a stop, SIGKILL (9) forces it without cleanup.
  4. 4A process killed by a signal exits with status 128 + the signal number.
  5. 5trap catches a signal or the end of the script (EXIT) to clean up properly.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.