1

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?

  • What do you want the lifetime of the lock to be? – Andy Dalton Mar 13 '18 at 14:40
2

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
  • 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 '18 at 15:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.