c - mmap 的最小尺寸
问题描述
使用 mmap 时,共享内存的最小大小是多少?我需要创建一个内存大小足够小的程序,它最多可以读取(或保存)几个字符。我怎么能这样做?
将大小更改为 1、2 或 4 时,它仍会读取整个字符串。
我基于How to use shared memory with Linux in C
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
void* create_shared_memory(size_t size) {
int protection = PROT_READ | PROT_WRITE;
int visibility = MAP_ANONYMOUS | MAP_SHARED;
return mmap(NULL, size, protection, visibility, 0, 0);
}
#include <string.h>
#include <unistd.h>
int main() {
char* parent_message = "hello"; // parent process will write this message
char* child_message = "goodbye"; // child process will then write this one
void* shmem = create_shared_memory(128);
memcpy(shmem, parent_message, sizeof(parent_message));
int pid = fork();
if (pid == 0) {
printf("Child read: %s\n", shmem);
memcpy(shmem, child_message, sizeof(child_message));
printf("Child wrote: %s\n", shmem);
} else {
printf("Parent read: %s\n", shmem);
sleep(1);
printf("After 1s, parent read: %s\n", shmem);
}
}
解决方案
为您收到的内存段保留的实际大小取决于操作系统。通常,在全页面虚拟内存系统上,系统以页面为单位为进程分配内存,这意味着,对于您的情况,将分配最小页面大小(在 32/64 位 linux 中为 4Kbytes)
对于小块内存,使用 is to callmalloc(3)
和它的朋友,因为这可以为您处理最小化系统调用次数和小于通常应用程序请求的页面块的内务。通常malloc(3)
是调用sbrk(2)
或memmap(2)
处理这个。
推荐阅读
- flutter - 对话框关闭时如何返回上一个屏幕?
- java - 线程“主”java.lang.ArrayIndexOutOfBoundsException 中的异常:索引 1 超出长度 0 的范围,不知道这是什么意思或如何修复它
- 3d - MeshLab 一次保存一个新的摄像机视图原来的网格消失了
- javascript - Weasyprint django - 生成一个空的 PDF
- html - 如何隐藏代码元素并在单击它们时显示它们 HTML
- javascript - 将名字和姓氏翻转为姓氏名字
- python - Discord bot问题“缺少必需的参数”python
- linux - 找到显示反斜杠
- c - 在 Windows 上进行 C 套接字编程时,我需要替换哪些等效的标头、函数和数据类型?
- android - 在页面中的颤振应用中显示文本段落