本文介绍了在linux中,如何为内存区域创建文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些程序可以处理文件或内存缓冲区中的某些数据.我想提供统一的方式来处理这些情况.

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.

我可以:1)映射文件,以便我们可以将它们作为内存缓冲区统一处理; 2)使用fopen和fmemopen创建FILE *,以便像FILE *一样统一访问它们.

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

但是,我不能使用上述任何一种方法.我需要将它们都当作文件描述符处理,因为我使用的其中一个库仅采用文件描述符,并且对文件描述符执行mmap.

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.

所以我的问题是,给定一个内存缓冲区(我们可以假定它与4K对齐),我们能否获得由该内存缓冲区支持的文件描述符?我在其他问题中看到popen是一个答案,但我认为popen中的fd不能被映射.

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.

推荐答案

您无法轻松地从某些内存区域"创建文件描述符(除了C标准库之外,这没有帮助).但是,您可以创建共享内存区域,以获取文件描述符作为回报.

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.

来自 shm_overview(7):

列出的接口中有mmap,这意味着您可以像对普通文件进行内存映射一样,对内存进行内存映射".

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.

因此,在两种情况下(文件或内存缓冲区)都使用mmap应该可以无缝运行,如果仅由您控制内存缓冲区"的创建.

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

这篇关于在linux中,如何为内存区域创建文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 23:37