File Lock on Linux

Viewed 1201

So there are 2 scripts: A and B, both want to write to the same file. It's possible to both scripts want to write to the file at the same time. How can I lock the file? While script A is writing to the file, script B has to wait till the file is get unlocked.

I tried this:

while [ -f $LOCK ]
do
    sleep 0.1
    done
touch $LOCK
#action
rm $LOCK

The problem with the script above that it's possible, that both of A and B is looking for the $LOCK at the same time, and they cant find't to start writing. Any help?

3 Answers

You can use kill -0 and if construction. For example:

kill -0 $lockPid
if [[ $? == 0 ]];then
    echo "File locked"
    break
else
    bash script2.sh
fi
Related