In linux , how to create a file descriptor for a memory region

Deadly 提交于 2020-01-12 06:50:07

问题


I have some program handling some data either in a file or in some memory buffer. I want to provide uniform way to handle these cases.

I can either 1) mmap the file so we can handle them uniformly as a memory buffer; 2) create FILE* using fopen and fmemopen so access them uniformly as FILE*.

However, I can't use either ways above. I need to handle them both as file descriptor, because one of the libraries I use only takes file descriptor, and it does mmap on the file descriptor.

So my question is, given a memory buffer (we can assume it is aligned to 4K), can we get a file descriptor that backed by this memory buffer? I saw in some other question popen is an answer but I don't think fd in popen can be mmap-ed.


回答1:


You cannot easily create a file descriptor (other than a C standard library one, which is not helpful) from "some memory region". However, you can create a shared memory region, getting a file descriptor in return.

From shm_overview (7):

shm_open(3)
Create and open a new object, or open an existing object. This is analogous to open(2). The call returns a file descriptor for use by the other interfaces listed below.

Among the listed interfaces is mmap, which means that you can "memory map" the shared memory the same as you would memory map a regular file.

Thus, using mmap for both situations (file or memory buffer) should work seamlessly, if only you control creation of that "memory buffer".




回答2:


You could write (perhaps using mmap) your data segment to a tmpfs based file (perhaps under /run/ directory), then pass the opened file descriptor to your library.



来源:https://stackoverflow.com/questions/12081720/in-linux-how-to-create-a-file-descriptor-for-a-memory-region

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!