#include <unistd.h>		// sysconf
#include <stdio.h>		// printf
#include <stdlib.h>		// exit
#include <fcntl.h>		// O_RDWR
#include <sys/mman.h>	// mmap
#include <string.h>		// strlen
#include <errno.h>		// errno

#define eprintf(args...) fprintf(stderr, ##args)

const char *DEVICE_PATH = "/dev/my_shmem";

int main(int argc, char *argv[])
{
	/* Have:
	 * - Different mm => different address space
	 * - Different virtual address
	 */
	void *addr = (void *) 0x10000000;

	const long PAGE_SIZE = sysconf(_SC_PAGESIZE);
	if (PAGE_SIZE == -1) {
		eprintf("Error retrieving page size: %d.\n", errno);
		exit(EXIT_FAILURE);
	}

	// open device file w/ RW perms
	FILE *fp = fopen(DEVICE_PATH, "r+");
	if (!fp) {
		eprintf("Error opening device %s: %d.\n", DEVICE_PATH, errno);
		exit(EXIT_FAILURE);
	}
	int fd = fileno(fp);
	if (fd == -1) {
		eprintf("Error retrieving file descriptor: %d.\n", errno);
		exit(EXIT_FAILURE);
	}

	// mmap device
	void *buf = mmap(addr, PAGE_SIZE * 2, PROT_READ | PROT_WRITE,
		MAP_SHARED, fd, 0);
	if (!buf) {
		eprintf("Error mmap-ing: %d.\n", errno);
		exit(EXIT_FAILURE);
	}

	// Write to mmap-ed device
	char to_write[] = {0x88, 0x77, 0x66, 0x55, 0x00};
	memcpy(buf, to_write, strlen(to_write));

	// Unmap device
	munmap(buf, PAGE_SIZE * 2);

	// Close device
	fclose(fp);

	printf("Finished!\n");
	exit(EXIT_SUCCESS);
}
