Bash & Shell Scripting (50 Qs)•Part 3: Advanced Text Processing & Production Internals (Senior / Lead)
File Locking in Bash with `flock`: Preventing multiple simultaneous cron executions.
senior LevelCode Examplebash-shellAdvanced Text Processing
In Simple Words:
When a cron job takes longer to run than its execution frequency (e.g., a 10-minute backup scheduled every 5 minutes), overlapping instances will thrash CPU and corrupt files.
flock uses kernel-level advisory file locking to ensure strictly one instance runs at any given time:
bash
#!/usr/bin/env bash
exec 200>/var/lock/nightly-sync.lock
flock -n 200 || { echo "Another sync instance is already running. Exiting."; exit 1; }
# Critical section starts here
echo "Performing exclusive backup..."
sleep 10
echo "Backup complete."