Course contentsShow
← Linux
Lesson 134 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Wait and Signal Synchronization

Coordinate background task completion using process wait primitives.

In this lesson, you will learn how to orchestrate multiple background processes so they finish in a predictable order using synchronization primitives.

The Problem: Asynchronous Chaos

When you launch multiple background tasks using the & operator, the shell loses track of their individual progress. If your script launches three heavy data-processing tasks, it cannot automatically know when they are finished unless you explicitly tell it to "wait" for them. Without synchronization, your script might attempt to process result files before the background tasks have even finished writing them.

Coordinating with wait

The wait command is your primary tool for synchronization. When you invoke wait without arguments, the script pauses and blocks execution until all background processes spawned in the current shell context terminate.

If you need to be more precise, you can provide the Process ID (PID) of a specific background task. The $! variable in Bash stores the PID of the most recently executed background command.

#!/usr/bin/env bash

# Start task A in the background
./process_data.sh A > output_A.log &
PID_A=$!

# Start task B in the background
./process_data.sh B > output_B.log &
PID_B=$!

# Wait specifically for Task A to finish
wait $PID_A
echo "Task A is done, but B might still be running."

# Now wait for everything else
wait
echo "All remaining background tasks have finished."

Signal Synchronization

While wait handles completion, "Signaling" allows your main script to communicate with background tasks while they are running. Using the kill command with specific signals (like SIGUSR1), you can tell a background process to pause, reload configuration files, or flush its memory to disk. Your background task must have a trap command ready to catch these signals, allowing you to orchestrate the internal state of your background work without stopping the main script.

By combining wait to track lifecycle completion and trap to handle signals, you transform a collection of disconnected background commands into a structured, synchronized system.

Key Takeaway: Use the wait command to pause your script until specific background PIDs finish, ensuring data integrity before moving to the next stage of execution.