简体   繁体   中英

mmap() and locking files

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?

尝试使用flock(2) ,其文档说“通过任何这些重复描述符上的显式LOCK_UN操作释放锁,或者所有这些描述符都已关闭。”

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM