文件锁定在clojure中
我正在使用Java Filelock
将文件锁定在Clojure(在MacOS上)。这是我获取锁定的代码:
(defn lock-file
[file-path]
(try
(let [file (io/file file-path)
channel (.getChannel (RandomAccessFile. file "rw"))]
(if-let [lock (.tryLock channel)]
channel
(do
(println (format "Lock on %s couldn't be acquired" file-path))
(System/exit 1))))
(catch OverlappingFileLockException _
(println (format "Lock on %s couldn't be acquired" file-path))
(System/exit 1))))
当两个过程都使用 lock-file
时,这起作用。
但是,即使文件被某些其他过程锁定,过程也可以使用 spit
写入文件。 Filelock
不保护它吗?
我无法理解 filelock
的用途是什么,如果它无法阻止它。
我想在文件上获取读写锁定。任何其他过程都无法读取/编写锁定文件。是否有一种惯用的混蛋方式?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,如果您想协调跨流程的事物,则需要操作系统的帮助:无需涉及操作系统,您无能为力地影响另一个过程。因此,找出要运行的操作系统,并查找是否以及如何管理文件锁定。例如,在Linux上,所有文件锁均为建议。您可以说:“嘿,我正在使用此文件,您可能不应该”。但是,如果另一个过程忽略了此建议,它仍然可以使用该文件。请参阅获得独家读/写锁有关原子更新的文件以进行进一步讨论。同样,讨论文件锁的行为如何在操作系统上变化。
If you want to coordinate things across processes, you need the operating system's help, of course: there's nothing you could do to affect another process without involving the OS. So, figure out what operating system you want to run this on, and look up if and how it manages file locks. On Linux, for example, all file locks are advisory. You can say, "hey, I'm using this file, and you probably shouldn't". But if another process ignores this advice, it can still use the file. See Obtain exclusive read/write lock on a file for atomic updates for some further discussion on this. Likewise the Javadoc for FileLock talks about how the behavior of file locks varies across operating systems.