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

Kan Li picture Kan Li · Aug 22, 2012 · Viewed 12.8k times · Source

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.

Answer

Damon picture Damon · Aug 24, 2012

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".