I have a bash script that is called by a program once a process is complete. I need a way for that bash script to wait if another instance of itself is running to exit before continuing. I can't just use lock files and exit because the script will not be called again on any kind of regular schedule.
3 Answers
I can't just use lock files and exit because the script will not be called again on any kind of regular schedule.
Within the script, before creating the lock file, you can loop through checking if the lock file exists, if it does, continue looping (through a sleep command or something) and when it goes away, create it.
Something like:
#!/bin/bash
while [ -e /var/tmp/bash_script.lock ];
do
sleep 5
done
touch /var/tmp/bash_script.lock
echo "do something"
rm /var/tmp/bash_script.lock
1 Comment
Davy Durham
umm.. bad race condition in doing it that way. imagine several processes trying to run.. First has the lock. Second and Third both see when First has ended and both touch the file, one removes the file before the other was finished and a Fourth could incorrectly get in.
If you don't want to wait indefinitely (i.e. notify user of possible problem)
TEST_LOCK=tests/_output/running
for i in $(seq 1 30)
do
if [ -f $TEST_LOCK ]
then # wait for other instances
echo "Lock file found, waiting for $i seconds"
sleep $i
else
break
fi
done
if [ -f $TEST_LOCK ]
then # waited too long
echo "Waited for the lock file too long" | mail -s "Staging tests failed" "[email protected]"
exit 99
fi
echo "$@ `date`" > $TEST_LOCK
#your code, then
rm -f $TEST_LOCK