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
// !> Concurrent sum using fork and shared memory via mmap.

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#include <assert.h>

int main(int argc, char **argv) {
  assert(argc > 1);
  int to = atol(argv[1]);
  
  unsigned long *sum = mmap(NULL, sizeof(unsigned long), PROT_WRITE | PROT_READ,
      MAP_SHARED | MAP_ANONYMOUS, -1, 0);
  /** 
   * There is a data race risk with this code!
   *
   * Exercise: add a semaphore lock. The lock needs to be shared.
  sem_t *sum_lock = mmap(..., sizeof(sem_t), ..., MAP_SHARED | MAP_ANON, ...);
  */
  assert(sum != NULL);
  *sum = 0;

  pid_t child = fork();
  assert(child != -1);

  if (child == 0) { // in the child process
    for (int i = 1; i <= to / 2; i++) { 
      *sum += i;
    }
    return 0;
  }
  else { // in the parent process
    for (int i = to / 2 + 1; i <= to; i++) { 
      *sum += i;
    }
  }

  assert(wait(NULL) != -1);
  printf("sum = %lu\n", *sum);
  munmap(sum, sizeof(unsigned long));
  return 0;
}