mmap()和锁定文件

前端之家收集整理的这篇文章主要介绍了mmap()和锁定文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请考虑以下代码段(错误处理故意丢失):
  1. void* foo(const char *path,off_t size) {
  2. int fd;
  3. void *ret;
  4.  
  5. fd = open(path,O_RDWR);
  6. lockf(fd,F_LOCK,0);
  7. ret = mmap(NULL,size,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  8.  
  9. close(fd);
  10. return ret;
  11. }

所以,想法是打开一个文件,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()?

解决方法

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

猜你在找的C&C++相关文章