4

I am looking at the flock docs:

http://www.tutorialspoint.com/unix_system_calls/flock.htm

https://linux.die.net/man/1/flock

I have this:

#!/usr/bin/env bash

temp_dir="$HOME/temperton/tmp";
mkdir -p "$temp_dir"

(

  flock -x "$temp_dir/a"
  echo '111'

) &

(

  flock -x "$temp_dir/a"
  echo '222'

) &

but when I run it I get this error:

flock: bad file descriptor: '/home/ratt/temperton/tmp/a'
flock: 111
bad file descriptor: '/home/ratt/temperton/tmp/a'
222
  • 1
    That is not how flock works. You need to supply both a file to lock and a command. Please look at [this](http://man7.org/linux/man-pages/man1/flock.1.html) manual page, it contains usage examples. – gudok Jun 09 '19 at 06:26
  • 1
    By *not* including a command to run, you're telling it to do the file descriptor based locking, but you're forgetting a couple of very important things for that to work. So yeah, look at the example in the man page again. – Shawn Jun 09 '19 at 10:54

1 Answers1

2

The 'flock' is the most useful then operates with a file descriptor. You should also provide a command to execute if locking on on file/dir-name. I guess, internally it works as the following:

    exec 4<$name # open
    flock 4
    <your_command_here>
    exec 4<&-    # close

In your example you can replace locks with

    flock $temp_dir sleep 5s

to check the difference.

Dmitry
  • 664
  • 8
  • 8
  • if you say exec 4<$name it will create a file called '4' AND also set the descriptor value to 4. But if you say exec 4<>$name it will just set the descriptor and not create the unnecessary 4 file. – Joseph Astrahan May 24 '22 at 00:35
  • no, this does not create file named '4' ;) – Dmitry May 27 '22 at 20:01
  • I could show you a video showing otherwise ;). It's possible it's a linux thing within a docker container for me though to be fair. – Joseph Astrahan May 29 '22 at 09:46