Consider this example, based on the example from the flock
man page:
#!/bin/bash
func() {
echo "$$ trying to acquire lock"
(
flock -e 42
echo "lock acquired by $$"
sleep 10
) 42> /tmp/mylock
echo "lock released by $$"
}
func
Now, if I run that script once:
$ bash ex.sh
22241 trying to acquire lock
lock acquired by 22241
lock released by 22241
If I run two instances within that 10-second sleep window of this script, the first in the background, a possible sequence of events is:
$ bash ex.sh& bash ex.sh
[1] 24518
24519 trying to acquire lock
24518 trying to acquire lock
lock acquired by 24519
lock released by 24519
lock acquired by 24518
$
lock released by 24518
In this example, the process the second process won the race and acquired the lock first. It then released the lock and allowed the first (the background) process to acquire, then release the lock.
I can improve the chances that the first process will win the race by introducing a delay between starting them:
$ bash ex.sh& sleep 1; bash ex.sh
[1] 30158
30158 trying to acquire lock
lock acquired by 30158
30179 trying to acquire lock
lock released by 30158
lock acquired by 30179
lock released by 30179