Unix File Lock: flock

To obtain a lock on a file, use flock command as per example:

#!/bin/ksh
####################################################################################################
# Modification Log (most recent first)                                                             #
# ====================================                                                             #
# Date        Author          Description                                                          #
# ====        ======          ===========                                                          #
# 20180822    Simon Vollett   Infra 636120: Modified to obtain an exclusive lock on the file. This #
#                             is to prevent multiple processes simultaneously reading the file and #
#                             returning the same number.                                           #
#                                                                                                  #
# Description: This script will pick up the last number allocated from file SEQUENCE_FILE in           #
#              $BASEDIR/data, increment this number and save it in the same file replacing the     #
#              last entry. New number is written out.                                              #
#                                                                                                  #
####################################################################################################
BASEDIR=$1
flock --exclusive --wait 60 $BASEDIR/data/SEQUENCE_FILE sh -c 'read count < ../data/SEQUENCE_FILE ; echo $((count + 1)) > ../data/SEQUENCE_FILE ; echo $((count + 1)) | tr -d "\n"'