Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
Michał Górny Avatar asked Nov 20 '11 16:11

Michał Górny


1 Answers

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."

like image 198
John Zwinck Avatar answered Sep 29 '22 06:09

John Zwinck