Mmap () and lock files

Consider the following code fragment (no error handling):

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 the file, mmap() and return only the data pointer. It would be great if the file could be locked for mmap-time too.

Per mmap(3p) :

The mmap () function adds an additional link to the file associated with file descriptor fildes, which is not deleted by the subsequent closing () of the descriptor in this file. This link should be removed if there are no more mappings for the file.

But behind lockf(3p) :

File locks should be released the first time the lock process closes any file file descriptor.

So, using lockf() , I would have to keep fd open and carry my link for a very long time. Is there a better portable method for securing a file lock until munmap() ?

+7
source share
2 answers

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

+5
source

No no. You have several options for ease of use:

  • Save the fd function.
  • Place the mutex inside the display area.
  • Use a separate lock file.

I will not go into details for them here, anyway there are other questions describing them.

0
source

All Articles