BASH / CHAPTER 11
Background jobs and explicit completion
AdvancedTrack child processes instead of assuming launch means success.
By the end of this chapter
- Capture a background process identifier
- Inspect wait status
- Coordinate multiple workers before cleanup
The idea
Appending & starts work asynchronously. The parent can continue before that work finishes, and successful launch does not establish successful completion. $! identifies the most recently started background job, so capture it promptly when later code must wait for that specific child. wait returns the child’s completion status, allowing the parent to report failure rather than ignoring it.
When several workers use a shared temporary resource, cleanup must wait until those workers have stopped using it. Cancellation requests and observed completion are separate events. Keep a list of worker identifiers, define whether one failure should stop remaining work, and wait for the relevant children before returning a final status. Do not infer completion from a fixed sleep duration, because scheduling and workload duration vary.
( exit 7 ) &
pid=$!
if wait "$pid"; then
printf 'success\n'
else
status=$?
printf 'failed:%s\n' "$status"
fifailed:7
The parent waits for the specific child and reports its nonzero completion status.
Try it yourself
Start two independent workers, wait for both, and fail the parent if either worker fails.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING