How to open file with exclusive lock?

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 12 15:54:55 PDT 2016


On Tue, Jul 12, 2016 at 03:40:36PM -0700, Charles Hixson via Digitalmars-d-learn wrote:
[...]
> OK.  It's not possible without OS support.  Agreed.  And I don't want
> to get into C calls, but rather to use the mechanisms that D provides.
> And this *probably* won't cause any problems.  But how should I tell D
> that that's the way I want to access to work?  It's not clear to me
> that locking beyond the current EOF is valid, or whether it will
> decide that it needs to reserve the space before I use it (in which
> case locking from 0->ulong.max bytes is a bad idea, and would totally
> fill my hard disk).

Here's another approach.

Since it's almost a given that we're talking about cooperating processes
sharing an advisory lock here (since a global mandatory file lock seems
to have poor support, at least on Posix), we don't *have* to lock the
actual bytes we're writing to. We can simply reserve a couple of bytes
(perhaps even just one byte) at the beginning of the file, and agree
among all processes that we will always try to acquire lock on that byte
before writing to (the rest of) the file.  Essentially it would serve as
a file equivalent of a mutex.  Then wrap all your file primitives in a
little wrapper that acquires this mutex before performing file I/O, have
your program only do I/O through this wrapper, and you're all set.

(IIRC, this is how the SQLite3 library implements database read/write
locks. Each sqlite3 database file has a few bytes, IIRC 6 bytes, at a
known file offset, that it uses to control various levels of access to
the database. Depending on which level of locking was needed, it would
acquire a lock on one or more of these bytes, before accessing the rest
of the file. It doesn't actually acquire a lock on the bytes being read
/ modified.)


T

-- 
If you're not part of the solution, you're part of the precipitate.


More information about the Digitalmars-d-learn mailing list