使用 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)
对于小块内存,使用方法是调用 malloc(3)
及其 friend ,因为这可以为您处理最小化系统调用次数和小于通常应用程序请求的页面 block 。通常是 malloc(3)
调用 sbrk(2)
或 memmap(2)
来处理这个问题。
关于c - mmap 的最小尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53581312/