Using the wait Command to Synchronize Processes
In this step, you will learn how to use the wait command to synchronize processes, making the parent process wait for the completion of background processes.
What is the wait Command?
The wait command is used in shell scripts to pause the execution of the script until one or more background processes have completed. This is particularly useful when you need to ensure that certain tasks finish before proceeding with subsequent operations.
Using wait Without Arguments
When used without arguments, the wait command waits for all background processes to complete.
Let's create a script that demonstrates this:
-
Navigate to your project directory:
cd ~/project
-
Create a new script:
nano wait_demo.sh
-
Add the following content to the script:
#!/bin/bash
echo "Starting background tasks..."
## Start two background tasks
./long_task.sh &
./long_task.sh &
echo "Waiting for all background tasks to complete..."
wait
echo "All background tasks have completed!"
-
Save and exit the editor by pressing Ctrl+O, then Enter, and finally Ctrl+X.
-
Make the script executable:
chmod +x wait_demo.sh
-
Run the script:
./wait_demo.sh
You'll see output similar to:
Starting background tasks...
Starting long task with PID 1236
Starting long task with PID 1237
Waiting for all background tasks to complete...
Long task completed
Long task completed
All background tasks have completed!
Notice that the message "All background tasks have completed!" only appears after both long tasks have finished. This demonstrates how the wait command pauses the script until all background processes complete.
Using wait with a Specific PID
You can also use wait to wait for a specific process by providing its PID:
-
Create another script:
nano wait_pid_demo.sh
-
Add the following content:
#!/bin/bash
echo "Starting background tasks..."
## Start two background tasks and capture their PIDs
./long_task.sh &
pid1=$!
./long_task.sh &
pid2=$!
echo "First process PID: $pid1"
echo "Second process PID: $pid2"
echo "Waiting for the first task to complete..."
wait $pid1
echo "First task has completed!"
echo "Waiting for the second task to complete..."
wait $pid2
echo "Second task has completed!"
-
Save and exit the editor by pressing Ctrl+O, then Enter, and finally Ctrl+X.
-
Make the script executable:
chmod +x wait_pid_demo.sh
-
Run the script:
./wait_pid_demo.sh
The output will show that the script waits for each process individually.
The $! variable contains the PID of the most recently executed background process. This allows you to capture and later use the PID with the wait command.