How can one open a file for exclusive access?

Parzival Herzog parz at shaw.SpamBucket.ca
Tue Jan 15 22:25:58 EST 2002


Thanks for the education, Alex.

In my humble opinion, I would expect that any OS that
offers general purpose multi-tasking would by default
provide n-readers exclusive-or one-writer locking
on opened files, and make special provision for other
types of sharing. This gives a guarantee of correct
operation or unambiguous failure to naive applications,
running in multi-tasking environment, just as memory
protection and separate process address spaces do.

Windows (NT, 2000) does offer such a locking model,
and then the stupid C library pisses that away, without
even suggesting in its documents, that this has been done.
Neither does the Posix documentation of open / fopen
have anything to say about the semantics of concurrent
file access.

Its too bad that such a fundamental part of  file operation
semantics is left to folklore.

I ended up writing a  class "UnsharedFile" that mimics
a builtin file type. Since it uses win32file, it produces
undocumented win32file exceptions, and I haven't tried to
map those to IOError exceptions, (way too much work,
and besides my class still wouldn't be a transparent
replacement for builtin files).

- Parzival


"Alex Martelli" <aleax at aleax.it> wrote in message
news:a21cgq$d4t$1 at serv1.iunet.it...
> "Parzival Herzog" <parz at shaw.SpamBucket.ca> wrote in message
> news:QRH08.82207$pP5.9625048 at news1.rdc1.mb.home.com...
>     ...
> > Now, it seems that non-shared file access is the Win32 default,
> > so can anyone explain why the Python "open", (which presumably
> > is based on the C library "open", which on Win32 is based on
> > "CreateFile", which defaults to non-shared access, ) gives me
>
> It's somewhat of a stretch to interpret an argument of 0 (whose
> meaning is not documented) as "defaulting".
>
> > unrestricted shared access? Who would want such a thing by
> > default?
>
> That's what C programmers are used to, perhaps in part because:
>
> > The argument between Alex and Syver suggests that in some or
> > is it all Unices, unrestricted shared access is the norm. Is that so?
>
> the open() system call, per se, does no locking on Unix.
>
>
> > It would seem that writing a robust portable program (i.e. it can
> > survive running a second instance of itself) for a simple
> > matter such as updating a file would be VERY difficult in Python.
>
> Not all that hard, depending on the kind of updates.  A typical
> approach is to prepare the updated-file at leisure then move
> it in place of the previous version atomically -- better than
> keeping a lock arbitrarily long.
>
>
> > BTW, if I were to use the file-locking  recipie Alex suggests,
> > then is it true (under Windows) that if the lock is not explicitly
> > released by the locking application, that it persists after the
> > application terminates?
>
> No.
>
>
> Alex
>
>
>





More information about the Python-list mailing list