Skip to content

Lesson 12 of 14 · 14m

Background Jobs, wait, and Bounded Parallelism

& and $! without orphans, wait -n as a worker-pool primitive, collecting child statuses, and when nohup is the wrong answer.

cmd & doesn't run a thread — it forks a child process your script now owns, in every sense. The child shares your open files, dies when you die unless you detach it, and reports its failure to nobody unless you collect it. A script that backgrounds work and forgets it is how you get orphaned rsync processes still writing after the deploy "finished". wait is the contract that closes the loop.

&, $!, and the jobs table

slow_backup &
pid=$!              # the child's PID
jobs -l             # live background jobs
kill "$pid"         # signal the child directly
wait "$pid"         # block until it exits — returns ITS exit status

wait with a PID returns that child's status, so wait "$pid" || echo "backup failed" is the correct shape. wait with no arguments waits for all children — and returns 0 unconditionally, discarding every failure that happened along the way. That distinction is the whole lesson in miniature: collect statuses individually, or you ran forty checks and learned nothing.

Bounded parallelism

wait -n (Bash 4.3+) returns when any one child finishes — with that child's status and, on Bash 5.1+, its PID in wait -n -p varname. This is the primitive for a worker pool:

max=8
for host in "${hosts[@]}"; do
  while (( $(jobs -rp | wc -l) >= max )); do wait -n; done
  check_host "$host" &
done
wait

jobs -rp lists running child PIDs; the loop keeps at most max in flight and wait -n reaps as slots free. Same fan-out xargs -P gives you — with variables, logging, and per-host status you control. For multi-line output per job, write > "/tmp/out.$host" inside the worker and aggregate after wait.

Exit statuses across a fan-out

fails=0
for pid in "${pids[@]}"; do
  wait "$pid" || ((fails++))
done
(( fails == 0 ))

wait $pid is the join. Skip it and set -e never sees the children fail — a script that printed forty "done"s after twenty silent timeouts.

Detaching: nohup, disown, setsid — and when not to

Sometimes the goal is the opposite: start something and leave. The escalating options:

nohup ./agent > agent.log 2>&1 &   # ignores SIGHUP, survives terminal close
disown                            # drop from the jobs table — shell forgets it
setsid ./agent < /dev/null > agent.log 2>&1 &   # new session, no controlling tty

nohup answers SIGHUP; disown removes the job so the shell won't HUP it at exit; setsid starts a new session entirely. They're the right tools for interactive detach — and the wrong ones for production. A detached process has no supervisor: nothing restarts it, nothing bounds its lifetime, nothing collects its exit. systemd-run (a transient service unit) or a real unit file gives you Restart=, RuntimeMaxSec=, and a journal. tmux new-session -d gives a human a detachable window. nohup & in a script you ship is a process nobody will ever find again.

coproc deserves a footnote: it starts a coprocess with pipes on both ends — coproc worker { ./worker; } then read -ru "${worker[0]}", printf 'go\n' >&"${worker[1]}". Fine for a persistent helper process inside one script; socat/nc or a fifo pair usually communicates the intent better.

Try this

for i in 1 2 3; do ( sleep $((RANDOM % 5)); exit $i ) & done
wait -n; echo "first done: $?"
wait; echo "all done"

The first wait -n reports whichever child died first — including its non-zero status. Then build the bounded-pool loop over 30 fake hosts and count in-flight jobs with jobs -rp | wc -l.

Pitfalls

  • $! is the last backgrounded PID — capture it immediately; a second & overwrites it.
  • ( cd /x && work ) & subshells isolate cd/vars — the parent never sees them. Sometimes the feature you want; sometimes the reason your edits "vanished".
  • kill %1 uses the jobs table, not the PID you stored — jobspecs do resolve in non-interactive shells, but slot numbers die with their job and can be reused. The $! you captured at spawn is unambiguous. Use $!.
  • wait on a PID that was never your child returns 127; an already-reaped child still reports its saved status — keep your PID list to children you started, reap once each.
  • Children inherit the script's traps context loosely — signals to the parent don't auto-forward; the signals lesson's kill "$child_pid" pattern is still required.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.