请考虑以下代码段(错误处理故意丢失):
- 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):
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.
但是对于lockf(3p):
File locks shall be released on first close by the locking process of any file
descriptor for the file.
因此,使用lockf()我必须保持fd打开并在非常长的时间内携带它的引用.是否有更好的可移植方法来确保文件被锁定,直到调用munmap()?