首页 > 解决方案 > 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);
  }
}

标签: clinuxunixmemorymmap

解决方案


为您收到的内存段保留的实际大小取决于操作系统。通常,在全页面虚拟内存系统上,系统以页面为单位为进程分配内存,这意味着,对于您的情况,将分配最小页面大小(在 32/64 位 linux 中为 4Kbytes)

对于小块内存,使用 is to callmalloc(3)和它的朋友,因为这可以为您处理最小化系统调用次数和小于通常应用程序请求的页面块的内务。通常malloc(3)是调用sbrk(2)memmap(2)处理这个。


推荐阅读