1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * @file shared.c
 *
 * Sharing memory between processes.
 */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>

#include <assert.h>

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;

}