简体   繁体   English

mmap的最小尺寸

[英]Minimal size for mmap

What is the minimal size for shared memory, when using mmap? 使用mmap时,共享内存的最小大小是多少? I need to create a program for which memory size will be small enough, that it will be able to read (or save) at most few chars. 我需要创建一个程序,其内存大小将足够小,以便最多可以读取(或保存)几个字符。 How Could I do that? 我该怎么办?

When changing size to 1, 2 or 4, it still reads the whole string. 当将大小更改为1、2或4时,它仍会读取整个字符串。

I'm basing on How to use shared memory with Linux in C 我基于如何在C中使用Linux共享内存

#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);
  }
}

The actual size reserved for the memory segment you receive is operating system dependant. 为您收到的内存段保留的实际大小取决于操作系统。 Normally, on a full paged virtual memory system, the system allocates memory for processes in page units, this means, for your case, the minimum page size will be allocated (this is 4Kbytes in 32/64bit linux) 通常,在全页面虚拟内存系统上,系统以页面为单位为进程分配内存,这意味着,对于您而言,将分配最小页面大小(在32/64位linux中为4KB)

For small chunks of memory, the using is to call malloc(3) and its friends, as this can handle for you the housekeeping of minimizing the number of system calls to do and the smaller than a page chunks that normally applications request. 对于较小的内存块,使用的是调用malloc(3)及其朋友,因为这可以为您处理最小化要执行的系统调用数量以及小于通常应用程序请求的页面块的内务处理。 It is normally malloc(3) that calls sbrk(2) or memmap(2) to handle this. 通常是malloc(3)调用sbrk(2)memmap(2)来处理此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM