mmap.c

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <errno.h>

#include "utils.h"

#define PAGE_SIZE 4096
#define BLOCK_SIZE 128

int main(int argc, char *argv[])
{
#ifdef NO_MAP
    char some_array[PAGE_SIZE];
#else
    // MAP_ANON is not fully POSIX as far as I understand the spec
    char *some_array = mmap(NULL, PAGE_SIZE, PROT_NONE, MAP_SHARED | MAP_ANON, 0, 0);
    printf("Mapped region is %p\n", some_array);
    exit_if(some_array == MAP_FAILED, "Map failed");
#endif

    switch(fork()) {
        case -1: exit_if(1, "Can't fork");
        case 0:
                 mprotect(some_array, PAGE_SIZE, PROT_WRITE);
                 for (int i = 0; i < PAGE_SIZE; i++)
                     some_array[i] = i % 10 + '0';
                 break;
        default:
                 mprotect(some_array, PAGE_SIZE, PROT_READ);
                 exit_if(wait(NULL) == -1, "wait");
                 for (int i = 0; i < (PAGE_SIZE / BLOCK_SIZE); i++)
                     printf("[%2d] %.*s\n", i, BLOCK_SIZE, some_array + i*BLOCK_SIZE);
                 break;
    };

    exit_if(
            munmap(some_array, PAGE_SIZE) == -1,
            "Unmap failed");
    return 0;
}