Return To Chapter Two

Page 149

#6. Write a shell script that produces a file of sequential numbers by reading the last number in the file, adding 1 to it, and then appending to the file. Run one instance of the script in the background and one in the foreground, each accessing the same file. How long does it take before a race condition manifests itself? What is the critical section? Modify the script to prevent the race
(Hint: use ln file file.lock to lock the data file).
First, initialize a file with one character 0. That is, type echo 0 > file under #.
                                                                                             (Note: echo string:     Echoes string to standard output.)
The following is a shell script:
i=0
while [ $i != 300 ]
do
i=`expr $i + 1`
n=`tail -1 file`
expr $n + 1 >> file
done

If we run the above script twice at same time, in the middle, the number which append to the file may not be shown in the sequential way. It may go back a few numbers then keep sequence to next numbers. That is the race condition occurred when one process read the number and immediately another process write a new number into the file. The first process may append a number after it. Thus, the inconsistent system occurs.

The following is another shell script (Take care race conditions):

i=0
while [ $i != 300 ]
do
if ln file file.lock
then
i=`expr $i + 1`
n=`tail -1 file`
expr $n + 1 >> file
rm file.lock
fi
done

If lock the file before one process reads and updates, and unlock the file after that, the inconsistent situation will be avoid.