Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

mmap

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.

like image 253
Kan Li Avatar asked Aug 22 '12 21:08

Kan Li


1 Answers

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

like image 147
Damon Avatar answered Sep 27 '22 22:09

Damon