Help: using msvcrt for file locking

Sheila King sheila at spamcop.net
Sun Aug 26 16:20:05 EDT 2001


On Sun, 26 Aug 2001 15:19:20 GMT, Sheila King <sheila at spamcop.net> wrote
in comp.lang.python in article
<0q4iotg9ld08s7850vv3dqfi2hnbefv015 at 4ax.com>:

:On Sun, 26 Aug 2001 10:23:22 GMT, bokr at accessone.com (Bengt Richter)
:wrote in comp.lang.python in article
:<3b88ceaa.496940252 at wa.news.verio.net>:
:
::I'm wondering if _locking requires using _sopen? The Python builtin open uses
::fopen as part of creating the file object, I believe. Example code in
::the msvc++6.0 help re _locking uses _sopen, which provides shared access control.
:
:Hmm. This may be the case???
:
:In an interactive session, when I try to acquire two non-blocking locks:
:
:>>> import os
:>>> filename = r'e:\apache\cgi-bin\pylinks\lock.txt'
:>>> size = os.path.getsize(filename)
:>>> f = open(filename)
:>>> fd = f.fileno()
:>>> msvcrt.locking(fd, msvcrt.LK_NBLCK, size)
:>>> g = open(filename)
:>>> gd = g.fileno()
:>>> msvcrt.locking(gd, msvcrt.LK_NBLCK, size)
:Traceback (most recent call last):
:  File "<interactive input>", line 1, in ?
:IOError: [Errno 13] Permission denied
:>>> 

Upon reading the Python docs for the msvcrt module, yet another time,
and thinking about this more carefully...

(The docs say, in part:
"
LK_LOCK
LK_RLCK
Locks the specified bytes. If the bytes cannot be locked, the program
immediately tries again after 1 second. If, after 10 attempts, the bytes
cannot be locked, IOError is raised.

LK_NBLCK
LK_NBRLCK
Locks the specified bytes. If the bytes cannot be locked, IOError is
raised.
"
)

It appears the LK_NBLCK tries for a blocking lock. Tries once, gives up
if not successful. Kind of strange they named it NBLCK. Seems like
non-blocking lock, but doesn't behave that way.

Whereas, LK_LOCK is a non-blocking lock. Well, tries 10 times, anyhow.

Appears that, via the msvcrt module, only exclusive locks are available,
no shared locks. From other reading I've done,
LK_LOCK and LK_RLOCK are the same. (One might think LK_RLOCK would be
fore a read lock, thus a shared lock, but that is not the case.)

OK, I think I'm OK, with this. I just won't try for a lock for reading
processes. I'll have some file there, that as long as it exists, reading
the file can proceed. Writers will delete that file before trying to
obtain an exclusive lock on the file. Then, when they unlock the file,
they can create that reading permission file again.


--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/




More information about the Python-list mailing list