// !> 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;
}