Recall & Review
beginner
What is the purpose of using a lock file in a script?
A lock file prevents multiple instances of the same script from running at the same time. It acts like a 'do not enter' sign to avoid conflicts or duplicated work.
Click to reveal answer
intermediate
How do you create a lock file safely in bash to avoid race conditions?
Use the 'mkdir' command to create a directory as a lock. This is atomic, so only one script can create it at a time. If 'mkdir' fails, another instance is running.
Click to reveal answer
beginner
What should a script do if it finds the lock file already exists?
It should exit or wait, because the lock means another instance is running. This avoids running two copies at once.
Click to reveal answer
intermediate
Why is it better to use a directory as a lock file instead of a regular file?
Creating a directory with 'mkdir' is an atomic operation in Unix systems, so it avoids race conditions. Creating a regular file is not atomic and can cause conflicts.
Click to reveal answer
beginner
Show a simple bash snippet that uses a lock directory to allow only one script instance.
if mkdir /tmp/myscript.lock 2>/dev/null; then
echo "Lock acquired, running script..."
# script commands here
rmdir /tmp/myscript.lock
else
echo "Another instance is running. Exiting."
exit 1
fi
Click to reveal answer
What does a lock file prevent in scripting?
✗ Incorrect
Lock files are used to prevent multiple instances of the same script from running at the same time.
Which command is best for creating an atomic lock in bash?
✗ Incorrect
'mkdir' is atomic and safe for creating lock directories, preventing race conditions.
What should a script do if it cannot create the lock directory?
✗ Incorrect
If the lock directory exists, it means another instance is running, so the script should exit or wait.
Why is using a regular file for locking less safe than a directory?
✗ Incorrect
Creating a regular file is not atomic, so two scripts might create it simultaneously causing conflicts.
What command removes the lock directory after the script finishes?
✗ Incorrect
'rmdir' removes an empty directory, which is used to release the lock.
Explain how to use a lock file to ensure only one instance of a bash script runs at a time.
Think about using mkdir as an atomic operation.
You got /4 concepts.
Describe why atomic operations are important when creating lock files in scripts.
Atomic means 'all or nothing' in one step.
You got /3 concepts.