How to open file with exclusive lock?

Charles Hixson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 12 15:40:36 PDT 2016


On 07/12/2016 12:05 PM, H. S. Teoh via Digitalmars-d-learn wrote:
> On Tue, Jul 12, 2016 at 11:54:18AM -0700, Charles Hixson via Digitalmars-d-learn wrote:
>> I want to open a file with an exclusive lock.  It would be important
>> that no other thread be able to access the file in write mode, and
>> desirable that no other thread be able to access the file in read
>> mode.  (Ditto for other processes.)
>>
>> stdio.file.lock (or is it stdio.file.File.lock?) seems to demand a
>> range of chunks to lock, but the file is not fixed in length. Is it
>> appropriate to just specify the maximum possible number of bytes (i.e.
>> ulong.max)?
> Whether this is even possible depends on your OS. I don't know of any
> cross-platform way of file-locking that is guaranteed to work
> everywhere.
>
> In Posix there's fcntl(F_RDLCK / F_WRLCK), which I believe is the
> underlying OS call for File.lock. However, this is only an *advisory*
> lock, i.e., any other processes accessing the file must also call
> flock(), otherwise none of its protections apply.  It only works between
> cooperating processes.
>
> Linux does have a mandatory locking feature, but it requires the kernel
> to be specially configured for it, and the filesystem must also support
> it (and must be mounted with the correct options). Unfortunately it's
> Linux-specific and probably won't work for any other OS.
>
> Windows may have some file-locking mechanism that does what you want,
> but I'm not familiar with the intricacies of how it works.
>
>
> T
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).


More information about the Digitalmars-d-learn mailing list