简体   繁体   English

我是否需要munmap()mmap()文件?

[英]Do I have to munmap() a mmap() file?

I have relatively new to C++ and I am learning from another guy's code. 我对C ++比较陌生,我正在向另一个人的代码学习。 His code reads from a mmapped file, but does not free any mapped memory in the end. 他的代码从一个映射文件读取,但最后没有释放任何映射的内存。 In my understanding, mmap() map files into virtual memory. 以我的理解,mmap()将文件映射到虚拟内存。 Don't I need to release those mapped memory in some way, like, calling munmap()? 我不需要以某种方式释放那些映射的内存,例如调用munmap()吗?

I believe you should release mapped memory with munmap. 我相信您应该使用munmap释放映射的内存。 But it will be released automatically (like close syscall for regular files or sockets) after exit(). 但是它将在exit()之后自动释放(例如,关闭常规文件或套接字的syscall)。 Remember, that implicit closing/unmapping is bad style! 请记住,隐式关闭/取消映射是不好的样式!

完成后,仅需使用munmap(),除非您的程序正在退出,否则无需这样做,它将在退出时自动取消映射该段。

munmap happens automatically on exit munmapexit时自动发生

So if the program is going to exit anyways, you don't really need to do it. 因此,如果该程序仍然要退出,则实际上并不需要这样做。

man munmap 4.15 says: man munmap 4.15说:

The munmap() system call deletes the mappings for the specified address range, and causes further references to addresses within the range to generate invalid memory references. munmap()系统调用删除指定地址范围的映射,并导致对该范围内地址的进一步引用以生成无效的内存引用。 The region is also automatically unmapped when the process is terminated. 进程终止时,该区域也会自动取消映射。 On the other hand, closing the file descriptor does not unmap the region. 另一方面,关闭文件描述符不会取消映射区域。

If the program doesn't exit, of course, you leak memory, just as with malloc (which nowadays uses mmap ). 如果程序没有退出,那么当然会泄漏内存,就像使用malloc (如今使用mmap )一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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