Bash & Shell Scripting (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How do you implement a File Lock (Mutex) to prevent concurrent script execution?
senior LevelCode ExampleSystem Design
In Simple Words:
Use the Linux utility flock:
- Creates an advisory file lock on a dedicated file descriptor:
bash
exec 200>/var/lock/my_cron_job.lock
if ! flock -n 200; then
echo "Another instance is already running! Exiting." >&2
exit 1
fi
# Critical section runs here safely...
-n: Non-blocking. Exits immediately if lock is already held by another running process.