#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <err.h>
#include <stdlib.h>
#define PAGE_SIZE 4096
#define STRING1 "Hello from first mapping!"
#define STRING2 "Greetings from second mapping!"
static void
print_string_at(const char *addr)
{
printf("At address %p: \"%s\"\n", (const void *)addr, addr);
}
int
main(void)
{
char *addr1, *addr2;
char template[] = "/tmp/mmap_test.XXXXXX";
int fd, prot, flags;
/* Create temporary file */
fd = mkstemp(template);
if (fd == -1)
err(1, "mkstemp failed");
/* Immediately unlink - file will persist until last fd is closed */
if (unlink(template) == -1)
err(1, "unlink failed");
/* Extend file to page size */
if (ftruncate(fd, PAGE_SIZE) == -1)
err(1, "ftruncate failed");
/* Set up protection and flags for mapping */
prot = PROT_READ | PROT_WRITE;
flags = MAP_SHARED;
/* Create first mapping */
addr1 = mmap(NULL, PAGE_SIZE, prot, flags, fd, 0);
if (addr1 == MAP_FAILED)
err(1, "First mmap failed");
/* Create second mapping of the same file */
addr2 = mmap(NULL, PAGE_SIZE, prot, flags, fd, 0);
if (addr2 == MAP_FAILED)
err(1, "Second mmap failed");
printf("Created two mappings of the same page:\n");
printf("addr1: %p\n", (void *)addr1);
printf("addr2: %p\n", (void *)addr2);
printf("\n");
/* Write to first mapping */
printf("Writing first string to addr1...\n");
strcpy(addr1, STRING1);
print_string_at(addr1);
print_string_at(addr2);
printf("\n");
/* Write to second mapping */
printf("Writing second string to addr2...\n");
strcpy(addr2, STRING2);
print_string_at(addr1);
print_string_at(addr2);
/* Clean up */
if (munmap(addr1, PAGE_SIZE) == -1)
err(1, "munmap failed for addr1");
if (munmap(addr2, PAGE_SIZE) == -1)
err(1, "munmap failed for addr2");
if (close(fd) == -1)
err(1, "close failed");
return (0);
}