OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

wait

We will demonstrate the wait command first. To do this, we will need two scripts, a par- ent script:


#!/bin/bash


# async-parent: Asynchronous execution demo (parent) echo "Parent: starting..."

echo "Parent: launching child script..." async-child &

pid=$!

echo "Parent: child (PID= $pid) launched."


echo "Parent: continuing..." sleep 2


echo "Parent: pausing to wait for child to finish..." wait $pid


echo "Parent: child is finished. Continuing..." echo "Parent: parent is done. Exiting."

#!/bin/bash


# async-parent: Asynchronous execution demo (parent) echo "Parent: starting..."

echo "Parent: launching child script..." async-child &

pid=$!

echo "Parent: child (PID= $pid) launched."


echo "Parent: continuing..." sleep 2


echo "Parent: pausing to wait for child to finish..." wait $pid


echo "Parent: child is finished. Continuing..." echo "Parent: parent is done. Exiting."


and a child script:



#!/bin/bash

# async-child: Asynchronous execution demo (child) echo "Child: child is running..."

sleep 5

echo "Child: child is done. Exiting."

#!/bin/bash

# async-child: Asynchronous execution demo (child) echo "Child: child is running..."

sleep 5

echo "Child: child is done. Exiting."


In this example, we see that the child script is very simple. The real action is being per - formed by the parent. In the parent script, the child script is launched and put into the background. The process ID of the child script is recorded by assigning the pid variable with the value of the $! shell parameter, which will always contain the process ID of the last job put into the background.

The parent script continues and then executes a wait command with the PID of the child process. This causes the parent script to pause until the child script exits, at which point the parent script concludes.

When executed, the parent and child scripts produce the following output:



[me@linuxbox ~]$ async-parent

Parent: starting...

[me@linuxbox ~]$ async-parent

Parent: starting...

Asynchronous Execution


Parent: launching child script... Parent: child (PID= 6741) launched. Parent: continuing...

Child: child is running...

Parent: pausing to wait for child to finish... Child: child is done. Exiting.

Parent: child is finished. Continuing... Parent: parent is done. Exiting.

Parent: launching child script... Parent: child (PID= 6741) launched. Parent: continuing...

Child: child is running...

Parent: pausing to wait for child to finish... Child: child is done. Exiting.

Parent: child is finished. Continuing... Parent: parent is done. Exiting.


Top OS Cloud Computing at OnWorks: