Winlock is a library that allows locking a file, using system calls, on Windows.
(winlock:with-locked-file (#p"~/some/file") (do-something))
The file can be opened for read, write, or both, and be shared (
:shared t) or exclusive (
(with-locked-file (file :direction :input :shared t))
:direction defaults to
:shared defaults to
nil otherwise. The direction can be any of
Note that the file is not opened by locking it.
with-locked-file, there are also unbalanced
unlock-handle functions. (There is no
unlock-file; you have to save the handle returned by lock-file to pass to
Caveat: the file that is locked is not actually the file itself, but another file with a
.lock extension. E.g. if you lock
file.txt, the actual lock is taken on
file.txt.lock. This is because once an exclusive lock is taken on a file, the file is accessible only through the handle used to lock it – even the same process cannot open the file with a different handle. You can circumvent this by calling
:direct t. In this case no lockfile is used and the file is locked directly.
Some code in this library (for error reporting) is adapted from winhttp.
This is intended as a building block for a portable file-locking library.