mmap() 和锁定文件

发布于 2024-12-17 11:09:39 字数 727 浏览 4 评论 0原文

考虑以下代码片段(故意缺少错误处理):

void* foo(const char *path, off_t size) {
    int fd;
    void *ret;

    fd = open(path, O_RDWR);
    lockf(fd, F_LOCK, 0);
    ret = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    close(fd);
    return ret;
}

因此,想法是打开一个文件,mmap() 它并仅返回数据指针。如果文件也可以在 mmap 时间锁定,那就太好了。

根据 mmap(3p)

mmap() 函数应添加对与该文件关联的文件的额外引用 文件描述符 fildes 不会被该文件上的后续 close() 删除 描述符。当没有更多映射时,应删除此引用 文件。

但根据 lockf(3p)

文件锁应在任何文件的锁定过程首次关闭时释放 文件的描述符。

因此,使用lockf()我必须保持fd打开并在很长一段时间内携带它的引用。是否有更好的可移植方法来确保文件在调用munmap()之前被锁定?

Consider the following snippet (error handling missing on purpose):

void* foo(const char *path, off_t size) {
    int fd;
    void *ret;

    fd = open(path, O_RDWR);
    lockf(fd, F_LOCK, 0);
    ret = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    close(fd);
    return ret;
}

So, the idea is to open a file, mmap() it and return just the data pointer. It would be great if the file could be locked for mmap-time too.

Per mmap(3p):

The mmap() function shall add an extra reference to the file associated with the
file descriptor fildes which is not removed by a subsequent close() on that file
descriptor. This reference shall be removed when there are no more mappings to
the file.

But per lockf(3p):

File locks shall be released on first close by the locking process of any file
descriptor for the file.

So, using lockf() I'd have to keep the fd open and carry its reference for an awfully long time. Is there a better portable method to ensure the file is locked till munmap() is called?

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

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

发布评论

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

评论(2

面犯桃花 2024-12-24 11:09:39

尝试使用flock(2),其文档说“锁是由显式释放的对任何这些重复描述符进行 LOCK_UN 操作,或者当所有此类描述符都已关闭时。”

Try using flock(2), whose documentation says "the lock is released either by an explicit LOCK_UN operation on any of these duplicate descriptors, or when all such descriptors have been closed."

一片旧的回忆 2024-12-24 11:09:39

不,没有。为了便于使用,您有几个选项:

  • 保持 fd 打开。
  • 在映射区域内放置一个互斥体。
  • 使用单独的锁定文件。

我不会在这里详细介绍它们,无论如何还有其他问题可以更好地描述它们。

No, there isn't. You have a few options, in order of ease of use:

  • Keep the fd open.
  • Put a mutex inside the mapped region.
  • Use a separate lock file.

I won't go into details for them here, there are other questions describing them better anyway.

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