🎓 A1Learner
🔍
0 of 45 lessons completed

Bash Process Groups

A Bash process group is a set of processes that the shell manages as one job. One signal to the group reaches the job leader and every child it started.

Stop a job, then resume it

Job control puts the sleep in its own group. STOP freezes it, the jobs list shows the frozen state, then CONT and a final kill end it.

set -m
sleep 5 &
kill -STOP %1
sleep 0.2
jobs
kill -CONT %1
kill %1
wait %1 2>/dev/null || true
echo "job handled"

One signal ends the whole group

The supervisor saves the job leader number, then signals the whole group with a minus sign before it. The trapped worker writes its note and exits.

set -m
( set +m; printf ready > ready.txt; trap 'printf "group stopped\n" > note.txt; exit 0' TERM; while :; do :; done ) &
pid=$!
for i in $(seq 1 50); do [ -f ready.txt ] && break; sleep 0.1; done
disown
kill -TERM -- -$pid
wait "$pid" 2>/dev/null || true
cat note.txt
echo "supervisor done"

Check whether a job is still alive

kill -0 sends no signal, so it only tests whether the job still exists. The two checks bracket the kill, and the second one proves the job is gone.

set -m
sleep 5 &
if kill -0 %1 2>/dev/null; then echo "job alive"; fi
kill %1
wait %1 2>/dev/null || true
if kill -0 %1 2>/dev/null; then echo "job alive"; else echo "job gone"; fi
echo "check done"

Example

set -m
( set +m; trap 'printf "worker stopped\n" > final.txt; exit 0' TERM; while :; do :; done ) &
pid=$!
sleep 0.2
echo "worker running"
kill -STOP -- -$pid
sleep 0.2
echo "worker paused"
kill -CONT -- -$pid
echo "worker resumed"
disown
kill -TERM -- -$pid
wait "$pid" 2>/dev/null || true
cat final.txt
echo "supervisor done"

Key points

  • Job control: set -m turns on job control in a script, so each background job gets its own process group.
  • Job spec: %1 names the first background job, so the script can signal it without naming a process number.
  • Group signal: killing a job sends the signal to the whole group, not just the leader.
  • Stop and resume: STOP freezes a whole job, and CONT lets it run again.
  • Session: a session is a set of process groups, and a terminal belongs to the foreground group.
  • Honest limit: a process that ignores or traps a signal may survive a group signal, so the script must check the result.

In this example, a worker runs in its own process group under job control. The supervisor first pauses the whole group, then resumes it, then ends it with a group signal. The trapped worker writes its final note before exiting, and the supervisor collects it.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Why does a supervisor signal a whole process group instead of only the job leader?