[Shell-Script] create a lock system for your code

Here is the code for making a lock system in your shell-script program.
The main utility of the lock system is to be sure to not running your code while another process of the same code is running.

The main principe is to create a lock file when the code is running, and check the existance of this file each time you're launching it.

NB : the variable $exec is the name of the script you want to execute.


#-- Parameters:
exec="./my-script.sh"
NAME="my-script"
LOCK="/tmp/${NAME}.lock"
out="/tmp/${NAME}-$(/bin/date '+%Y%m%d').out"

#-- Error Function:
error () {
echo "$1" 1>&2
exit 1
}

#-------------------------
# Launch the code
#-------------------------
if [ -f "$LOCK" ]
then
if [ "$(ps -p `cat $LOCK` | wc -l)" -gt 1 ]; then
#-- process is still running
echo "Quit at start: lingering process `cat $LOCK`"
error "Daemon already running (not launched)!"
exit 10
else
#-- process not running, but lock file not deleted
echo "process not running, but lock file not deleted"
rm $LOCK
echo $$ >> "$LOCK"
fi
else
echo "create lock"
echo $$ >> "$LOCK"
echo "done (pid=$$)"
# launch the code:
ksh ${exec} >> $out 2>&1

fi

rm $LOCK


1 comment:

Unknown said...

Locking does not work this way: Race condition is possible when two processes do not find the file a both create it. The pid file even would contain both pids or a mixture of both.