3

I'm learning file locking using flock(2), and I want to write a little C++ utility class to handle the locking. I've read quite a lot online, but there is one part I don't understand.

In e.g. Optimal lock file method:

1: open the lock file creating it if it doesn't exist
2: ask for an exclusive lock an agreed byte range in the lock file
3: when the lock is granted then
    4: <do my processing here>
    5: release my lock
    6: close the lock file
end

What is this lock file? I read that it is used for lock administration, but I thought that was exactly what flock(2) is used for? So why do we need to create an additional file? And why isn't this file deleted after I stopped needing the lock? Doesn't this mean that for every file I ever opened (with this locking method enabled) there is a lock file somewhere?

Would be great if someone could explain this or point me to some resource, I've already spent multiple hours on this.

picklepick
  • 1,370
  • 1
  • 11
  • 24
  • `flock` operates on a file descriptor, not on a file. The difference is in `If a process uses open(2) (or similar) to obtain more than one descriptor for the same file, these descriptors are treated independently by flock().` The answer you linked doesn't discuss `flock` but using a general separate lock file. – KamilCuk Nov 13 '19 at 12:56
  • So if I want to edit myfile.txt, using `open(2)` I get the file descriptor, and then I pass that fd to `flock(2)`. I still don't understand why I would create an extra lock file, what is that file used for? – picklepick Nov 13 '19 at 13:05
  • The answer you linked doesn't discuss `flock`. What would do without `flock`? You could create a separate lock file. The lock file, if exists, means the file is locked. Because `open(... O_CREAT | O_EXCL)` should be atomic, you can check if a file exists at the same time create the file. – KamilCuk Nov 13 '19 at 13:06
  • 1
    This method is used when the thing you want to lock is not a file. – user253751 Nov 13 '19 at 13:21
  • 1
    Thanks for helping! There are several answers in that thread that discuss `flock` though. The answer of 'chmike' for example first creates a lock file `int fd = open( lockName, O_RDWR|O_CREAT, 0666 );` and then uses flock on that file: `if( fd >= 0 && flock( fd, LOCK_EX | LOCK_NB ) < 0 )`. Maybe I'm confusing something here, but to me it seems like an extra lock file is created for each file I want to open and then the lock is applied to that file and not the original file. I don't understand why though. – picklepick Nov 13 '19 at 13:28
  • 2
    @user253751 ah ok, so just to be clear, if I use `flock` on a text file, there is no need to create a separate lock file? Because that's exactly what my prof wants me do in an assignment. But I have no idea why and from your answers and what I read on other sources, I understand that this is nonsensical? – picklepick Nov 13 '19 at 17:24

0 Answers0