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