文件锁定在clojure中

发布于 2025-01-31 07:14:14 字数 778 浏览 1 评论 0 原文

我正在使用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 的用途是什么,如果它无法阻止它。

我想在文件上获取读写锁定。任何其他过程都无法读取/编写锁定文件。是否有一种惯用的混蛋方式?

I'm using Java FileLock to lock files in Clojure (on macOS). This is my code to acquire a lock:

(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))))

This works when both the processes are using lock-file.

But a process can write to a file using spit even if the file is locked by some other process. Does FileLock not protect against that?

I'm failing to understand what is the use of FileLock if it can't prevent this.

I want to get a read-write lock on a file. Any other process should not be able to read/write the locked file. Is there an idiomatic Clojure way of doing this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅沫记忆 2025-02-07 07:14:14

当然,如果您想协调跨流程的事物,则需要操作系统的帮助:无需涉及操作系统,您无能为力地影响另一个过程。因此,找出要运行的操作系统,并查找是否以及如何管理文件锁定。例如,在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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文