Writing multi-process application in UNIX-Shell

Sometimes you need to improve performance of an application where UNIX shell script need to start a several process. The solution below can help you if application logic allows to run them in parallel, and application will not advance to the next step till all started processes are finished.

The solution have two parts. First part is to start processes simultaneously:

totalProc=4
idx=0

while [[ $idx -lt $totalProc ]]
do
  # will wait for each OS
  if [[ ${CHILDS[$idx]} -gt 2 ]]
  then
    # starting child process
    ${executable name} 2>&1 > ${logname}.log &
    CHILDS[$idx]=$!
  fi
  idx=$(( $idx + 1 ))
done

Next step is to wait till child processes are finished:

idx=0
while [[ $idx -lt $totalProc ]]
do
  # will wait for each OS
  if [[ ${CHILDS[$idx]} -gt 2 ]]
  then
    echo "===================== waiting for ${CHILDS[$idx]}"
    PID=${CHILDS[$idx]}
    wait $PID
    CHILDS[$idx]=$?
    if [[ ${CHILDS[$idx]} -ne 0 ]]
    then
      # process failed
    else
      # process finished
    fi
  fi
  idx=$((idx+1))
done

This script will wait for all children processes one by one in order they were created.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

WP Like Button Plugin by Free WordPress Templates