0

I have an existing lock file sometimes used by other processes. I want to temporarily acquire this lock file so other programs that potentially use it have to wait for me to unlock. Then I want to run a few commands, and then unlock it. How do I do this? I thought this would be easy but for some reason I cannot figure it out at all. I understand that I would most likely need to use flock for this, but what arguments should I be using in this scenario? flock seems to always need a command or second file to work, however in this situation there doesn't seem to be one.

Context: A bash script I am using is running into race conditions around a particular lock file (/var/lib/apt/lists/lock to be specific), and to test my solution I want to reliably be able to lock this file so I can check if my changes to the script work.

Dan
  • 543
  • 5
  • 17
  • [This](https://en.wikipedia.org/wiki/File_locking) is an overview on the topic. Look especially at the sectons labelled _Problems_ and _Lock files_ – user1934428 Feb 26 '21 at 07:59

1 Answers1

3

You have an example in the flock (1) man page. You should execute the commands in a subshell:

(
    flock -n 9 || exit 1
    ...
) 9>/var/lib/apt/lists/lock

Using this form the lock is released when the subshell exits.

Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43