Question

I've found boilerplate flock(1) code which looks promising. Now I want to understand the components before blindly using it.

Seems like these functions are using the third form of flock

flock [-sxun] [-w timeout] fd

The third form is convenient inside shell scripts, and is usually used the following manner:

(
 flock -s 200 
 # ... commands executed under lock ... 
) 200>/var/lock/mylockfile

The piece I'm lost on (from the sample wrapper functions) is this notation

eval "exec $LOCKFD>\"$LOCKFILE\""

or in shorthand from the flock manpage

200>/var/lock/mylockfile

What does that accomplish?

I notice subsequent commands to flock passed a value other than the one in the initial redirect cause flock to complain

flock: 50: Bad file descriptor

It seems like flock is using the file descriptors as a map to know which file to operate on. In order for that to work though, those descriptors would have to still be around and associated with the file, right?

After the redirect is finished, and the lock file is created, isn't the file closed, and file descriptors associated with the open file vaporized? I thought file descriptors were only associated with open files.

What's going on here?

Was it helpful?

Solution

200>/var/lock/mylockfile

This creates a file /var/lock/mylockfile which can be written to via file descriptor 200 inside the sub-shell. The number 200 is an arbitrary one. Picking a high number reduces the chance of any of the commands inside the sub-shell "noticing" the extra file descriptor.

(Typically, file descriptors 0, 1, and 2 are used by stdin, stdout, and stderr, respectively. This number could have been as low as 3.)

flock -s 200

Then flock is used to lock the file via the previously created file descriptor. It needs write access to the file, which the > in 200> provided. Note that this happens after the redirection above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top