3

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 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
1

use ps -df command which lists all the PIDs and PPIDs running on your system. Now you can include a code that will parse ps -df output and check for running instances of bash script iy answer is yes exit 1 the present script

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.