3 ms·
Why prevent others from reading the file? I guess mainly to avoid them reading mid-update in an inconsistent state. But preventing the read completely until yo
by jo909 10y ago
Why prevent others from reading the file? I guess mainly to avoid them reading mid-update in an inconsistent state.
But preventing the read completely until you are done writing the file is arguably also not "consistent", the reader wants a file and gets an error instead.
So now the reader has to either error out or implement some error handling, like waiting a bit which is rather impractical. But wouldn't it be nicer if he just got the "old" version of the file until you are finished with the update and "commit" the new file?
- Asooka 10y agoYes, it would be quite nice. But this version is simpler, and you can implement your version by writing to a temporary file, then doing an atomic rename. My operating model assumes a user creating some kind of content using an application. E.g. Photoshop is running and the user is editing a file. Photoshop can very well write partial updates to the file, so it's important that nobody else write to it, or you end up with a corrupted file. Maybe just opening the file with no locking mode should always succeed though, or there can be an additional LOCK_NONE for that case (I don't want to participate in the locking scheme and yes I want to read whatever data is there). In that case you're saying "I just want to read what's there even if it is not consistent right now". The LOCK constants should probably also be named FORBID, in the sense that you're opening the file and FORBIDding the operation from happening while you have it open. So you can forbid writing (because inconsistent data is nonsensical for this case) or reading and writing (because you'll be updating the file). But I think the LOCK names are easier to use, since you're specifying the operation you'll be doing and can be understood analogous to read/write locks.
- jo909 10y agoYou can also "forbid" others from reading and writing your file if use a new temporary file they don't know about, and weakly enforce that by removing the file system entry with unlink while keeping the fd open, then link it again later. Part of the goal is IMHO not having to write out the entire file every time, only because you changed a few bytes. The atomic renaming can't do that, to my knowledge. I'm really only wondering about the forbidding reads part, and if that gains anything useful. For a process that knows about and participates in the locking process that's already possible, but mandatory file locks are also for processes that did not participate. Like for example cat, the backup process etc.