/** * @file shared.c * * Sharing memory between processes. */ #include #include #include #include #include #include #include int main(int argc, char **argv) { int *shared = mmap( NULL, // no address hint sizeof(int), // enough pages to hold one int PROT_READ | PROT_WRITE, // read-write permissions MAP_ANON | MAP_SHARED, // anonymous (no file) and shared across processes -1, // no file 0); // no offset if (shared == MAP_FAILED) { perror("mmap of shared error"); exit(1); } *shared = 123; pid_t pid = fork(); assert(pid != -1); if (pid == 0) { // child printf("child: %d\n", *shared); // initial value is the same in both processes *shared *= 2; // modify in child printf("child: %d\n", *shared); // change visible in child exit(0); } else { // parent printf("parent: %d\n", *shared); // initial value same in both processes wait(NULL); printf("parent: %d\n", *shared); // change visible in parent because of sharing } return 0; }