Wednesday, March 19, 2014

S&P 4 – loops in backgrond

Came to know recently that even loops, similar to running a command, can run on background.
Adding a "&" makes a command to run in background.                                                                     Similar to that, even loops can be run on background.
#!/bin/bash
# background-loop.sh
for i in 1 2 3 4 5 6 7 8 9 10 # First loop.
  do
    echo -n “$i “
    sleep 1 # we will need to test with this sleep and without this sleep
done & # Run this loop in background.
# Will sometimes execute after second loop.
 echo first loop # This ‘echo’ sometimes will not display.
 
 for i in 11 12 13 14 15 16 17 18 19 20 # Second loop.
    do
       echo -n “$i “
       sleep 1  # we will need to test with this sleep and without this sleep
    done
echo # This ‘echo’ sometimes will not display.
 
# ======================================================
# without the sleep 1, the expected output from the script:
# 1 2 3 4 5 6 7 8 9 10
# 11 12 13 14 15 16 17 18 19 20
 
# Sometimes, though, you get:
# 11 12 13 14 15 16 17 18 19 20
# 1 2 3 4 5 6 7 8 9 10 bozo $
# (The second ‘echo’ doesn’t execute. Why?)
 
# Occasionally also:
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# (The first ‘echo’ doesn’t execute. Why?)
 
# Very rarely something like:
# 11 12 13 1 2 3 4 5 6 7 8 9 10 14 15 16 17 18 19 20
# The foreground loop preempts the background one.
exit 0
 
with that sleep 1, its really funny.

No comments:

Post a Comment