Menu

#8 file locking

open
nobody
None
5
2010-03-13
2010-03-13
No

The "Files and directories" page could include a section on file locking, like this:
--

File locking is not in the Common Lisp standard. However, the following macro should work in most cases:

(defmacro with-file-lock ((path &key interval) &body body)
"Get an exclusive lock on a file. If lock cannot be obtained, keep
trying after waiting a while"
(let ((lock-path (gensym))
(lock-file (gensym)))
`(let ((,lock-path (format nil "~a.lock" (namestring ,path))))
(unwind-protect
(progn
(loop
:for ,lock-file = (open ,lock-path :direction :output
:if-exists nil
:if-does-not-exist :create)
:until ,lock-file
:do (sleep ,(or interval 0.1))
:finally (close ,lock-file))
,@body)
(ignore-errors
(delete-file ,lock-path))))))

another solution is calling the underlying system locking facilities, e.g. on SBCL you can use sb-posix:fcntl.

Discussion


Log in to post a comment.