Skip to content

Instantly share code, notes, and snippets.

@ytxmobile98
Last active November 15, 2021 19:13
Show Gist options
  • Select an option

  • Save ytxmobile98/c37c948b067b23ce754475a1629ba923 to your computer and use it in GitHub Desktop.

Select an option

Save ytxmobile98/c37c948b067b23ce754475a1629ba923 to your computer and use it in GitHub Desktop.
Shared memory demo using mmap
// Note: to compile, you must link with -lrt.
// cc mmap_demo_main.c -o main.out -lrt
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
static const unsigned int SLEEP_TIME = 5;
int main(void) {
const size_t MAPPING_SIZE = sizeof(int);
int* i_ptr = (int*)malloc(MAPPING_SIZE);
int fd = -1;
void* mapping = mmap(i_ptr, MAPPING_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, fd, 0);
if (mapping == (void*)-1) {
free(i_ptr);
return EXIT_FAILURE;
}
int* m_ptr = (int*)mapping;
*m_ptr = 1;
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
else if (pid == 0) {
// child waits for a while, then write 0 to shared memory
sleep(SLEEP_TIME);
*m_ptr = 0;
}
else {
// parent waits until child writes 0 to shared memory
while (*m_ptr) {
continue;
}
pid_t wret = 0;
int wstatus = 0;
while ((wret = waitpid(-1, &wstatus, 0)) != -1) {
printf("Terminated pid %d\n", wret);
}
}
free(i_ptr);
munmap(mapping, MAPPING_SIZE);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment