Skip to content

Instantly share code, notes, and snippets.

@panta
Created March 21, 2022 10:37
Show Gist options
  • Save panta/7cf8a3839d4ed8936a4aafb07a5b80eb to your computer and use it in GitHub Desktop.
Save panta/7cf8a3839d4ed8936a4aafb07a5b80eb to your computer and use it in GitHub Desktop.
Simple example of shared memory between parent and child using mmap() and fork().
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
int main(int argc, char *argv[]) {
size_t size = 4096;
char *smem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
if (!smem) {
perror("mmap() failed");
exit(1);
}
pid_t child = fork();
if (child == 0) {
/* child */
sprintf(smem, "Hello!");
} else {
/* parent */
sleep(1);
printf("got: '%s'\n", smem);
if (waitpid(child, NULL, 0) < 0) {
perror("waitpid() failed");
}
munmap(smem, size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment