2

I was confused for a very long time with the meaning of the -n flag for flock(1).

Basically there are many guides for this tool, and often what we see is some command like flock -n 100. Here, fd number 100 is associated with some lockfile and used to perform locking.

Today I kept getting confused because I would do some simple tests, and flock would exit with failure immediately.

What exactly does the -n flag of flock do? Am I right in thinking that -n 100 associates file descriptor number 100 with some lockfile?

terdon
  • 242,166
Steven Lu
  • 2,282
  • Thanks for posting this, but could you please make it an actual question? I don't understand what you are asking here. – terdon Mar 07 '24 at 18:05
  • Yeah let me figure out what would have been the burning question i had from before i solved it. – Steven Lu Mar 07 '24 at 18:07

1 Answers1

1

It took me a long time to figure out that I misunderstood and made a dangerous assumption. I assumed from seeing it called with -n 100 to specify fd 100, that -n was the flag to set the file descriptor number. This isn't the case.

-n is for nonblocking and this flag causes the immediate failure upon failure to lock. From man flock:

-n, --nb, --nonblock

Fail rather than wait if the lock cannot be immediately acquired. See the -E option for the exit status used.

It seems that if a plain number is given, then it is treated as the fd. This is nonobvious.

terdon
  • 242,166
Steven Lu
  • 2,282
  • This is nonobvious As far as I can tell it's documented in the flock(1) man page. The Synopsis section at the top gives three examples of the command and argument syntax, and the third syntax is flock [options] number. The Description section (just under Synopsis) describes the three syntaxes. The first two don't show number as an argument. The description of the third syntax says: The third form uses an open file by its file descriptor number. See the examples below for how that can be used. – Sotto Voce Mar 07 '24 at 23:41
  • The manpage definitely did clear it all up for me. I suppose that my point is that the examples I saw and the choice of having the short flag named n turned out to be misleading for me. I made this post because it's going to help out others who get confused in the same process. – Steven Lu Mar 12 '24 at 09:16