Course outline

Bash / Advanced: channels, concurrency, and maintainable CLI design / Lesson 21

Collect background job outcomes reliably

Track owned child processes, wait for each result, and report batch failure without assuming completion order.

About 20 min read20 worked examples20 practice exercisesContent reviewed
On this page

Lesson goals

  • Capture process identifiers for owned background jobs.
  • Wait for and aggregate each child status.
  • Describe cleanup and concurrency limits separately.
  • Preserve individual child statuses while collecting every owned job.
  • Select a bounded collection strategy and distinguish process status from external effects.

Define ownership before backgrounding

A background command begins work concurrently with the parent, but its launch does not prove the work succeeded. The parent must know which child processes it owns and when it is safe to report a final result. The examples start exactly two harmless subshells and record each identifier immediately. A real batch needs a bounded number of active jobs, an interrupt policy, and a decision about whether remaining work continues after failure.

Collect every status

The first example stores each $! in an array and waits for each recorded child. It aggregates any nonzero outcome into failed while continuing to wait for the remaining child. Output from the two jobs can appear in either order. Waiting in array order does not change the order in which jobs actually complete, and printing a message when a job starts is not evidence of completion.

bash Wait for two successful jobs
pids=()
(printf "job one\n") & pids+=("$!")
(printf "job two\n") & pids+=("$!")
failed=0
for pid in "${pids[@]}"; do
  if wait "$pid"; then :; else failed=1; fi
done
printf "failed=%s\n" "$failed"

Each recorded PID is waited for and any nonzero status sets the aggregate flag.

Exercise a failing child

The second example replaces the work with one successful and one intentionally failing subshell. The parent still waits for both and prints failed=1. The if condition handles a nonzero wait status explicitly instead of treating it as an ordinary successful result. Run the blocks independently. A production script should return a documented nonzero status to its caller when its batch fails, rather than only printing a flag.

bash Detect a failing child
pids=()
(exit 0) & pids+=("$!")
(exit 3) & pids+=("$!")
failed=0
for pid in "${pids[@]}"; do
  if wait "$pid"; then :; else failed=1; fi
done
printf "failed=%s\n" "$failed"

One child exits with status 3, so the aggregate flag is set after both waits.

Bound and clean up the work

Two fixed jobs form a bounded demonstration, not a general-purpose worker pool. For many inputs, start new work only when capacity is available, retain identifiers and associated inputs, and wait for all owned children. On interruption, define how to signal and reap children without affecting unrelated processes. A child may itself create descendants, so process-tree cleanup requires an explicit platform and process-group design; do not assume one signal undoes external effects.

Verify completion and failure

Use controlled child commands with known exit statuses and different durations. Confirm all owned children are waited for, the final flag reflects at least one failure, and no success is reported before the slow child exits. Test an interrupted parent in an isolated environment and verify the documented cleanup behavior. Keep output ordering out of assertions unless the application deliberately serializes it; check status and effects instead.

Keep the launch record in the parent

A background list returns control before the work has completed. Its immediate status describes the asynchronous launch, not the eventual result. Capture $! immediately after each launch, before another asynchronous command changes it. Store the identifier next to a stable input label, because a numeric PID alone does not say which item failed. A simple pair of indexed arrays works when one parent launches and collects a fixed batch. The label is application data; quote it and never use its contents as shell syntax.

The parent shell that launched the job must perform the wait. A subshell or command substitution has its own child environment and is not a general collector for its parent’s children. Do not pass PIDs to another shell and assume it can recover their statuses. A saved identifier is also not a durable job receipt: process identifiers can be reused after a process ends. Keep the collection lifecycle short and avoid treating old PIDs as authority to signal arbitrary processes.

Collect statuses without losing their meaning

A wait with an explicit child identifier returns that job’s status. Put the wait in an if condition and save $? in the else branch immediately, before printf or another command replaces it. Writing if ! wait ... and then reading $? inside the branch instead captures the inverted status, not the child’s original status. A status of zero means successful termination according to that command’s contract; a nonzero number needs interpretation by the caller and does not by itself explain the underlying cause.

Continue through all recorded identifiers even after one failure if the policy is collect-all. Record each result and separately calculate the batch result. An array-order wait is simple and deterministic in reporting order, but can delay observation of a later job that already finished. It does not make the jobs run sequentially. A bare wait has different semantics and is not a substitute for individually collecting the failure of each named job. An empty batch should have a deliberate outcome rather than inheriting an unrelated previous status.

Choose the unit whose outcome matters

An asynchronous pipeline is one shell job, but its status depends on pipeline rules. Normally a pipeline reports its last command’s status; with pipefail enabled it reports the rightmost nonzero command status, or zero if all succeed. If the batch must treat a producer failure as failure even when the consumer succeeds, establish pipefail inside the launched subshell and wait for that subshell. This does not preserve every component status: use PIPESTATUS inside the executing shell immediately after the pipeline if individual component diagnostics are required.

A child can exit successfully while a detached descendant is still running, and a successful process can also produce invalid data. Decide whether the owned unit is a direct child, a pipeline, or a deliberately managed process group, and validate outputs separately from exit status. Shell status is a small numeric interface, not a transaction log. For external operations, retries and reconciliation require an application-level idempotency or recovery contract; waiting cannot roll back a partial effect.

Separate collection order from capacity

For a small fixed batch, launch a known number and wait for each PID. For many inputs, the limit must apply while launching, not only after all jobs have already started. One portable-to-older-Bash design starts a group of at most N jobs, waits for every member, clears the group, then starts the next group. This wave approach can leave a slot idle while the slowest member finishes, but it is easier to reason about than a continuously refilled pool.

Bash also provides wait -n and, in versions that support it, -p to identify a completed job. Check the actual target Bash version and its manual before using those options; a script written for a newer Bash can fail on an older installation. A refilled pool must remove exactly the completed identifier, preserve the associated label, handle nonzero completion without abandoning other children, and distinguish no remaining children from a job failure. Test that bookkeeping explicitly rather than assuming the order in which jobs finish.

Design interruption and verification together

If a signal interrupts wait, its status and any trap behavior must be considered separately from normal child completion. A trap can request shutdown, but a safe design also defines which currently owned children receive a signal and how the parent waits for them afterwards. Do not use a broad process-name match, and do not assume killing one direct child also kills its descendants. Process groups require a deliberate platform-specific design; effects already committed externally remain committed unless the application compensates them.

Test with synthetic children and a private temporary directory. Use synchronization markers or pipes to prove a slow child has started and to release it, rather than relying on a fragile sleep duration as proof of ordering. Assert the aggregate exit code, each labeled result, and the presence or absence of expected files after all waits. Include one nonzero child, an empty batch, a child that finishes early, and an interrupted run. These checks establish the behavior of the tested Bash and fixture, not a guarantee about remote systems or every signal race.

20 worked examples

1. Capture before another launch

Problem: Collect the two child results without losing either PID.

  1. Each launch replaces $!, so append the identifier immediately.
  2. Both waits happen in the launching shell before the count is printed.
bash Capture before another launch
(exit 0) & a=$!
(exit 0) & b=$!
count=0
for p in "$a" "$b"; do if wait "$p"; then ((count+=1)); fi; done
printf "success=%s\n" "$count"
Expected output
success=2

Why this result follows: Both recorded children return zero, giving two successes.

2. Preserve a failure code

Problem: Record the exact status of a child that exits with 7.

  1. The if condition handles a failing wait without terminating the script.
  2. The else branch saves $? before printf can overwrite it.
bash Preserve a failure code
(exit 7) & p=$!
if wait "$p"; then rc=0; else rc=$?; fi
printf "status=%s\n" "$rc"
Expected output
status=7

Why this result follows: The saved value is the status returned by wait.

3. Avoid the negation trap

Problem: Diagnose why negating wait hides the original failure code.

  1. The child returns 4, making wait fail.
  2. The ! operator reverses that failure, so the branch sees zero.
bash Avoid the negation trap
(exit 4) & p=$!
if ! wait "$p"; then printf "observed=%s\n" "$?"; fi
Expected output
observed=0

Why this result follows: The branch observes the negated command status, not 4.

4. Keep collecting after failure

Problem: Collect three statuses despite the middle child failing.

  1. The array preserves all three launch identifiers.
  2. A nonzero result increments failures but does not exit the loop.
bash Keep collecting after failure
pids=()
for s in 0 5 0; do (exit "$s") & pids+=("$!"); done
failed=0; seen=0
for p in "${pids[@]}"; do if wait "$p"; then :; else ((failed+=1)); fi; ((seen+=1)); done
printf "seen=%s failed=%s\n" "$seen" "$failed"
Expected output
seen=3 failed=1

Why this result follows: All three children are collected and exactly one failed.

5. Empty batch

Problem: Define the result when there are no children to launch.

  1. The empty array causes the loop body to be skipped.
  2. The initialized counters still describe the empty batch.
bash Empty batch
pids=(); seen=0; failed=0
for p in "${pids[@]}"; do if wait "$p"; then :; else ((failed+=1)); fi; ((seen+=1)); done
printf "seen=%s failed=%s\n" "$seen" "$failed"
Expected output
seen=0 failed=0

Why this result follows: No previous command status is mistaken for a batch failure.

6. Map labels to outcomes

Problem: Associate two input labels with their individual statuses.

  1. Parallel arrays associate each label with the PID at the same index.
  2. The parent prints in index order after waiting for each child.
bash Map labels to outcomes
labels=(alpha beta); pids=()
(exit 2) & pids+=("$!")
(exit 0) & pids+=("$!")
for i in 0 1; do if wait "${pids[i]}"; then rc=0; else rc=$?; fi; printf "%s=%s\n" "${labels[i]}" "$rc"; done
Expected output
alpha=2
beta=0

Why this result follows: The result remains associated with its input regardless of completion order.

7. Pipeline default status

Problem: Observe a failing producer followed by a successful consumer.

  1. The left command exits 3 but the right command consumes an empty stream successfully.
  2. Without pipefail, the pipeline status is the last command status.
bash Pipeline default status
( (exit 3) | cat >/dev/null ) & p=$!
if wait "$p"; then rc=0; else rc=$?; fi
printf "status=%s\n" "$rc"
Expected output
status=0

Why this result follows: The successful consumer masks the producer failure under default pipeline rules.

8. Pipeline with pipefail

Problem: Make the same kind of producer failure visible to the parent.

  1. The launched subshell enables pipefail before running its pipeline.
  2. The pipeline reports its nonzero producer status to wait.
bash Pipeline with pipefail
( set -o pipefail; (exit 3) | cat >/dev/null ) & p=$!
if wait "$p"; then rc=0; else rc=$?; fi
printf "status=%s\n" "$rc"
Expected output
status=3

Why this result follows: The parent receives 3 because pipefail exposes the failing component.

9. Return a batch result

Problem: Convert an observed failure to a documented batch exit code.

  1. The inner Bash collects the child status in its own environment.
  2. It exits 1 for any failure; the outer shell records that contract.
bash Return a batch result
bash -c '(exit 9) & p=$!; if wait "$p"; then exit 0; else exit 1; fi'
printf 'batch=%s\n' "$?"
Expected output
batch=1

Why this result follows: The caller receives the documented aggregate status rather than the child code.

10. Observe an unknown child

Problem: Check what happens when waiting for a numeric ID that is not a child.

  1. The deliberately invalid identifier is not a job of this shell.
  2. The error is suppressed for a stable demonstration; the returned status is captured.
bash Observe an unknown child
if wait 999999999 2>/dev/null; then rc=0; else rc=$?; fi
printf "status=%s\n" "$rc"
Expected output
status=127

Why this result follows: Bash returns 127 for an identifier that is not an active child of this shell.

11. Wait in a subshell

Problem: Test whether another shell environment can collect the parent’s child.

  1. The parent starts and retains the child identifier.
  2. A subshell has a different child table, so its wait cannot collect that identifier.
bash Wait in a subshell
(sleep 0.1) & p=$!
( if wait "$p" 2>/dev/null; then r=0; else r=$?; fi; printf "subshell=%s\n" "$r" )
wait "$p"
Expected output
subshell=127

Why this result follows: The original parent remains responsible for waiting for its child.

12. Bare wait does not aggregate failures

Problem: Compare a bare wait with a failed child.

  1. The child exits 8 after launch.
  2. A bare wait waits for active background jobs but returns zero rather than their individual statuses.
bash Bare wait does not aggregate failures
(exit 8) &
wait
printf "bare=%s\n" "$?"
Expected output
bare=0

Why this result follows: Use explicit identifiers when the batch needs each outcome.

13. Wait order with synchronization

Problem: Wait for a marker-dependent child before collecting the marker writer.

  1. The marker writer may finish before or after the first child sees the marker.
  2. The parent waits for the first PID and then collects the writer’s status regardless of their completion order.
bash Wait order does not set completion order
d=$(mktemp -d) || exit 1
trap 'rm -rf -- "$d"' EXIT
( while [[ ! -e "$d/ready" ]]; do :; done; exit 0 ) & a=$!
( : > "$d/ready"; exit 6 ) & b=$!
wait "$a"
if wait "$b"; then r=0; else r=$?; fi
printf "second=%s\n" "$r"
Expected output
second=6

Why this result follows: The second result remains available after the first wait completes.

14. Status is not output validation

Problem: Detect invalid data even when the child reports success.

  1. The child writes an unexpected value and exits zero.
  2. The parent checks both the status and the actual value.
bash Status is not output validation
d=$(mktemp -d) || exit 1
trap 'rm -rf -- "$d"' EXIT
( printf "bad\n" > "$d/result"; exit 0 ) & p=$!
if wait "$p" && [[ $(cat "$d/result") == ok ]]; then echo accepted; else echo rejected; fi
Expected output
rejected

Why this result follows: A zero exit status alone does not establish data correctness.

15. Two bounded waves

Problem: Process three jobs in waves of at most two.

  1. The first wave launches two children and waits for both.
  2. Only after those waits does the second wave launch the final child.
bash Two bounded waves
total=0
for wave in "0 2" "0"; do
 pids=(); for s in $wave; do (exit "$s") & pids+=("$!"); done
 for p in "${pids[@]}"; do if wait "$p"; then :; else ((total+=1)); fi; done
done
printf "failures=%s\n" "$total"
Expected output
failures=1

Why this result follows: Each wave is drained before the next begins, and one child fails.

16. Rightmost pipeline failure

Problem: Determine which failure pipefail returns for two failures.

  1. Both pipeline components exit nonzero.
  2. With pipefail the rightmost nonzero status is 5, not necessarily the earliest failure.
bash Rightmost pipeline failure
( set -o pipefail; (exit 3) | (exit 5) ) & p=$!
if wait "$p"; then r=0; else r=$?; fi
printf "status=%s\n" "$r"
Expected output
status=5

Why this result follows: Pipeline position selects the result, not a timing race.

17. Component status snapshot

Problem: Save both pipeline statuses inside the child.

  1. PIPESTATUS must be copied immediately after the pipeline.
  2. The child prints its snapshot before exiting normally, and the parent waits.
bash Component status snapshot
( (exit 3) | (exit 0); s=("${PIPESTATUS[@]}"); printf "parts=%s,%s\n" "${s[0]}" "${s[1]}" ) & p=$!
wait "$p"
Expected output
parts=3,0

Why this result follows: The snapshot preserves both component statuses before printf changes shell state.

18. Explicit batch success policy

Problem: Allow an empty batch but fail when a child returns nonzero.

  1. The initialized failure flag defines empty input as success.
  2. A failing child changes the flag and the function returns that value.
bash Explicit batch success policy
batch() { local failed=0 p; local -a ids=(); for s in "$@"; do (exit "$s") & ids+=("$!"); done; for p in "${ids[@]}"; do if wait "$p"; then :; else failed=1; fi; done; return "$failed"; }
if batch; then echo empty=0; fi
if batch 0 4; then echo mixed=0; else echo mixed=1; fi
Expected output
empty=0
mixed=1

Why this result follows: The function returns the documented aggregate instead of a last-child status.

19. Separate stderr by job

Problem: Keep two diagnostics associated with their jobs.

  1. Each child redirects standard error to its own private file.
  2. After both waits the parent reads the files in label order.
bash Separate stderr by job
d=$(mktemp -d) || exit 1
trap 'rm -rf -- "$d"' EXIT
( echo first >&2 ) 2>"$d/a" & a=$!
( echo second >&2 ) 2>"$d/b" & b=$!
wait "$a"; wait "$b"
printf "a=%s b=%s\n" "$(cat "$d/a")" "$(cat "$d/b")"
Expected output
a=first b=second

Why this result follows: Separate files avoid relying on interleaving of concurrent diagnostics.

20. Status after intervening command

Problem: Show why a failure must be saved before logging.

  1. The child exits 6 and the wait in the condition fails.
  2. The successful colon replaces the current status before it is printed.
bash Status after intervening command
(exit 6) & p=$!
if wait "$p"; then :; else :; printf "late=%s\n" "$?"; fi
Expected output
late=0

Why this result follows: The colon status is zero; save the wait result before any intervening command.

Common errors and fixes

The batch reports success immediately

Why it happens
Launching a background command was mistaken for its completion.
How to fix it
Record the PID and wait for the owned child.
Prevent it next time
Test with a controlled slow child and assert final timing by synchronization.

A child failure is lost

Why it happens
The parent did not inspect each wait status.
How to fix it
Aggregate each nonzero status and return the documented batch result.
Prevent it next time
Include a failing child among successful ones.

Cleanup affects an unrelated process

Why it happens
A broad process match was used instead of tracking owned children.
How to fix it
Track explicit identifiers and use a deliberate process-group policy when needed.
Prevent it next time
Test interruption in an isolated environment with unrelated processes untouched.

20 practice exercises

1. If the second child exits first, does the parent miss it?

Show hint

Consider where Bash retains a completed child’s status and which shell performs the waits.

Show worked solution

No. The parent has recorded both identifiers and waits for each. The first wait can block until its child finishes; the second wait then obtains the already completed child’s status, subject to the shell’s job handling.

The parent can wait for the first child and then retrieve the second child’s saved status, even if the latter finished earlier. Capture both identifiers promptly and collect them in the same shell; completion order is independent of wait order.

Check your solution

  • Both identifiers are saved immediately after their launches.
  • The explanation distinguishes actual completion order from the order of waits.

2. Does waiting for a child undo a partial remote write?

Show hint

Separate observing a process status from reversing its side effects.

Show worked solution

No. wait only observes the child’s completion status. Recovery or retry of external effects requires a separate documented contract, including how to handle an ambiguous outcome.

Waiting only obtains a termination status; it cannot undo a write already accepted by a remote service. A recovery design needs an application-level record, idempotency or reconciliation and must address ambiguous outcomes.

Check your solution

  • The answer says the partial write is not automatically undone.
  • The answer names a separate recovery or reconciliation policy.

3. A batch launches statuses 2, 0 and 7. Design a collector that reports each status and returns 1 when any failed.

Show hint

Save each PID and associate it with a label before another launch.

Show worked solution

Launch the three children, append each $! with its label, and loop over all identifiers. Use if wait and save $? in else; report 2, 0, and 7 respectively, then return 1 after every wait.

Check your solution

  • All three labeled statuses are reported.
  • The aggregate is 1 even though the second child succeeds.

4. A script launches a child and then another before saving $!. Diagnose the missing association and repair the launch sequence.

Show hint

Identify which asynchronous command most recently changed $!.

Show worked solution

The saved value identifies only the second asynchronous launch. Move the first assignment directly after the first launch and save the second immediately after its launch; wait for each saved identifier in the parent.

Check your solution

  • Two different identifiers are retained while both children are active.
  • Each wait is associated with the intended launch.

5. A child exits 12, but the failure branch prints zero after logging. Explain and repair the status capture.

Show hint

Consider what $? contains after a successful logging command.

Show worked solution

The logging command replaces the wait status with its own zero status. Assign rc=$? as the first command in the else branch, then log using rc; the reported child status is 12.

Check your solution

  • The saved value is 12.
  • Logging occurs only after the assignment.

6. A three-stage child pipeline has statuses 4, 0 and 6. Design a report that retains all component statuses and a batch failure flag.

Show hint

Capture PIPESTATUS inside the pipeline shell before running a reporting command.

Show worked solution

Enable pipefail in the child and copy PIPESTATUS immediately after the pipeline into an array. Write the three values 4, 0, 6 to a per-job result file and explicitly exit nonzero; the parent waits, reads that file, and sets its batch failure flag. A single wait status alone cannot reconstruct all three component results.

Check your solution

  • The report contains all three component statuses in pipeline order.
  • The parent sets the batch failure flag after collecting the child.

7. Five tasks have durations 1, 10, 1, 1 and 1 units in launch order. Compare waves of two with a refilled pool limited to two, assuming no overhead.

Show hint

Track both occupied slots and when each task becomes eligible to start.

Show worked solution

Waves finish at times 10, 11 and 12, so the batch ends at 12. A refilled pool runs the first two at time zero and starts tasks three, four and five in the free slot at times 1, 2 and 3; it ends at 10. Both limit concurrency to two, but the pool needs more completion bookkeeping.

Check your solution

  • The wave schedule finishes at 12 units.
  • The refilled schedule finishes at 10 units without exceeding two active tasks.

8. A zero-status child writes an empty result where a nonempty record is required. Define acceptance checks.

Show hint

Treat exit status and data validity as separate conditions.

Show worked solution

Wait for the child and reject any nonzero status. After a zero status, test that the expected file exists and is nonempty; this fixture must be rejected despite the successful process exit.

Check your solution

  • The zero status alone does not accept the output.
  • An empty file causes rejection.

9. For an empty input list, define a batch result and explain why relying on the previous command is wrong.

Show hint

Initialize the aggregate before the loop.

Show worked solution

Choose success for an empty batch and initialize failed=0 before launching anything. No waits occur; return that explicit value rather than the status of an unrelated earlier command.

Check your solution

  • No child is launched.
  • The returned status is zero by policy.

10. The parent starts a child but sends its PID to bash -c for waiting. Explain the failure and redesign collection.

Show hint

Determine which shell owns the child.

Show worked solution

The new Bash process is not the child’s parent and cannot collect its status as an owned job. Have the launching shell perform wait and pass the resulting status or a structured report to other processes.

Check your solution

  • The wait stays in the launching shell.
  • The report carries a result rather than assuming the PID is transferable.

11. A batch uses bare wait and receives zero after one child exits 8. Redesign it to detect that failure.

Show hint

Compare a wait with and without an explicit identifier.

Show worked solution

Capture the PID immediately and use if wait "$pid"; then record zero; else save $? immediately. For several children repeat this for each identifier and combine failures after all have been collected.

Check your solution

  • The child status 8 is recorded.
  • Every recorded child is waited for individually.

12. Two children write diagnostics concurrently. Design a report that associates each message with its input without assuming output order.

Show hint

Give each child a separate output destination.

Show worked solution

Redirect each child’s stderr to a distinct file in a private temporary directory associated with its input label. Wait for both, then read the files by label; clean the directory after reporting.

Check your solution

  • Each message remains associated with its label.
  • The report does not depend on interleaving.

13. A pipeline has component statuses 2, 0 and 6 under pipefail. Predict the status and explain what information it loses.

Show hint

Use pipeline position rather than completion time.

Show worked solution

The pipeline returns 6 because it is the rightmost nonzero component. This single value loses the earlier status 2; copy PIPESTATUS immediately in the executing shell if both failures are needed.

Check your solution

  • The result is 6.
  • The missing status 2 is identified.

14. A parent must stop launching new work after a failure but still collect already launched children. Specify the policy.

Show hint

Separate stopping launches from abandoning waits.

Show worked solution

Set a stop flag when a collected child fails, do not start further inputs, and continue waiting for every already recorded PID. Report both the failure and the inputs never launched so callers can decide what remains.

Check your solution

  • No new input starts after the failure is observed.
  • All children already launched are collected.

15. A child can spawn a descendant and exit before it. Explain why waiting for the child is insufficient for tree cleanup.

Show hint

Distinguish direct child completion from descendant lifetime.

Show worked solution

The direct child’s exit says nothing conclusive about a detached descendant. Define a platform-specific process-group and ownership policy if the entire tree must be signalled and collected; also account separately for already committed effects.

Check your solution

  • The child wait does not prove descendant completion.
  • The proposed policy addresses the process tree explicitly.

16. Design a controlled test showing that a parent waits for a slow child before its final report.

Show hint

Use an explicit synchronization event instead of a timing guess.

Show worked solution

Have the child signal readiness and block on a pipe until the test releases it. Verify no final report exists before release, then release it and verify the report appears after the child terminates.

Check your solution

  • No final report is present while the child is blocked.
  • The final report appears after release and collection.

17. A child writes half a remote record and exits nonzero. Decide what wait establishes and what recovery needs.

Show hint

Separate observed status from the state of the remote system.

Show worked solution

The nonzero wait establishes that the process failed, not whether the remote operation committed. Use an application-level identifier and reconciliation or an idempotent retry contract before deciding whether to repeat or compensate the write.

Check your solution

  • The result does not assert automatic rollback.
  • The recovery plan addresses an ambiguous remote outcome.

18. For labels red, blue and green, collected statuses are 0, 3 and 5. Build a report that distinguishes retryable status 3 from permanent failure 5 while returning batch failure.

Show hint

Classify each saved status only after collecting it, and keep the original label.

Show worked solution

Record red as success, blue as retryable, and green as permanent failure. Wait for every PID before the final report, keep the labels with their statuses, and return a nonzero batch status because two jobs failed. A retry policy must separately decide whether retrying blue is safe.

Check your solution

  • The report associates blue with retryable and green with permanent failure.
  • The batch result is nonzero and all three results are present.

19. A pool uses wait -n -p on an unknown Bash version. State a compatibility check and a fallback.

Show hint

Do not assume every installed Bash supports the same wait options.

Show worked solution

Check the target Bash version and its documented wait options during deployment. If the required options are absent, launch bounded waves and wait for each recorded PID; document that the fallback may leave slots idle.

Check your solution

  • The target environment is checked before relying on -p.
  • The fallback remains bounded and collects all launched children.

20. A signal interrupts a parent during wait. Outline a safe test and shutdown policy for its owned children.

Show hint

Avoid broad process-name matches and use an isolated fixture.

Show worked solution

In a disposable environment, record owned child identifiers, arrange a trap that requests shutdown, signal only the intended active children under a defined policy, and wait for them. Verify an unrelated fixture process remains untouched and all owned children terminate.

Check your solution

  • The unrelated fixture process remains alive.
  • The parent collects its owned children before finishing.

Key takeaways

  • Capture and wait for every owned child before reporting completion.
  • Bound concurrency and define interrupt and external-effect policies.
  • Capture each $! immediately in the launching shell.
  • Save a failing wait status before another command replaces it.
  • A collected status is not a rollback of external work.

Official references