0

What is the minimal size for shared memory, when using 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.

I'm basing on 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);
  }
}
Michał
  • 43
  • 1
  • 7
  • 2
    `sizeof parent_message` is `sizeof(char*)`. And mmap() counts in memory pages (mostly 4096 bytes) so your size (4 or 8) is rounded up, (but the tail is discarded when reading/writing to an actual disk file) – wildplasser Dec 02 '18 at 16:22
  • If you want `sizeof` to work as expected then use `const char parent_message[] = "hello";`. It will include the terminating `NULL` character. The same applies to `child_message`. In this case I think it is better to use a `COUNTOF` macro that fails on pointers. Something like [Array-size macro that rejects pointers](https://stackoverflow.com/q/19452971/608639). – jww Dec 02 '18 at 17:08
  • These also look problematic: `printf("Child read: %s\n", shmem);` (and friends). I don't see where you terminate the copied string with a `NULL`. – jww Dec 02 '18 at 17:18

1 Answers1

0

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)

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. It is normally malloc(3) that calls sbrk(2) or memmap(2) to handle this.

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31