Pages

Multi-Processing in bash

Advanced programmers and script writers must have been familier with the concepts  of multi threading/multi processing. Many of the high level commands support them. However, scripting languages also support them. Recently, I have been dealing with one of such interesting problem in bash scripts.
Given is an example of a script that spawns a new child process in the background and the main process continues.

#!/bin/sh
print_info(){
PROCESS_MESSGAE=$1
LAST_SPAWNED_PID=$!
DATE_TIME=`date`
echo "Process Info : $PROCESS_MESSGAE, TIME=$DATE_TIME ,PID=$LAST_SPAWNED_PID"
}
(
i=0
while [ "$i" -lt 100 ]
do
echo $i
sleep 2
i=$((i+1))
done
) &
PID_LAST_SPAWNED=$!
print_info "While loop and process info check"
sleep 10
kill $PID_LAST_SPAWNED
The block of code that is written between single braces “()”, will run in the new process. Any command followed by an ampersant “&” will run on background, independent with the parent process. So the program is creating a background process which prints the values of $i in a while loop.
The main process grabs the process_id ie “PID” of the process, and then kills it after 10 seconds. So the background process could only print up to 5.

No comments:

Post a Comment

If you like to say anything (good/bad), Please do not hesitate...