2

I derived a sample bash script from what I have seen around, regarding bash flock function. I do:

func()
{
    42>/home/foo
    flock -e 42 || exit 1
    echo "hello world"
    sleep 5
}

Then I consecutively run func&, each of which prints hello world immediately, whereas I expect the first one to print the message and the rest to exit. What am I missing here?

1
  • What do you want the lifetime of the lock to be? Mar 13, 2018 at 14:40

1 Answer 1

3

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
1
  • Oh god I'm so stupid. 42>/home/foo does absolutely nothing in that context, it should be placed after execution block, not inside. It did work with: func() { flock -e 42; echo "hello world."; sleep 3 } and call it with func 42>/home/foo &. Thanks for the inspiration :)
    – corsel
    Mar 13, 2018 at 15:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .