Prevent Overlapping Cron Runs (flock)
When a job runs longer than its interval, cron starts the next copy before the last one finishes, and the two collide. The standard fix is flock: give each job a lock file and use flock -n so a second instance exits immediately instead of piling up. No application code changes are needed.
The one-line fix
Run the job under a non-blocking lock:
* * * * * /usr/bin/flock -n /tmp/backup.lock /usr/local/bin/backup.sh
-n means "fail fast": if the lock is held, the new run exits with status 1 and does nothing. Drop -n to make it wait for the lock instead, and add -w 30 to wait at most 30 seconds.
Why flock and not a PID file
Home-made PID-file checks race and leave stale files after a crash. flock uses a kernel advisory lock tied to the file descriptor, so the lock is released automatically when the process dies — even on kill -9.
One lock per job
Give every job its own lock path (/tmp/backup.lock, /tmp/sync.lock). Sharing one lock across unrelated jobs will serialise them unintentionally.
FAQ
How do I stop two copies of a cron job running at once?
Wrap the command in flock -n with a per-job lock file: * * * * * /usr/bin/flock -n /tmp/job.lock /path/to/script.sh. A second run exits immediately while the first holds the lock.
What is the difference between flock -n and plain flock?
With -n the second run fails fast and skips. Without -n it blocks and waits for the lock; add -w SECONDS to cap the wait.
Is flock better than a PID file?
Yes. flock is a kernel lock released automatically when the process ends, so it survives crashes and kill -9 without leaving a stale lock, unlike hand-rolled PID files.