Approach to File Locking?
Hi there,
I'm writing a class which can be used to read/write files. I want to implement file locking, and wondering how best to achieve it in Linux.
I understand that to lock files using fcntrl(), I must open them with 'open()', rather than 'fopen()'. However, fopen() implements read/write buffering, whereas open() usually does not.
As I see it, I have two options:
1. When the class opens a file, it also created a 'lock file' beside it. Presumably, the main file is opened using fopen(), whereas the lock file is created with open() and then locked. When opening an existing file, my class should therefore check for an existing lock file to determine whether the file can be opened in the required mode. I understand that this is a pretty standard approach.
Alternatively, I could implement the following approach and was wondering what people think:
2. Use the open() call to open/create a single main file only (i.e. no extra lock file), and fcntrl() to lock it. However, because read/writes are unlikely to be buffered, I would have to implement my own buffering within the workings of my class.
Is there any overriding reason why I should go with option 1 over option 2?
Thanks