#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/user.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

const char *data = "Hello, world!\n";

int main (int argc, char *argv[])
{
	bool write_goes_first = false;

	if (NULL != getenv("SF_WRITE_GOES_FIRST")) {
		write_goes_first = true;
	}

	/* Wait for write. */
	if (true == write_goes_first) {
		sleep(1);
	}

	int fd = open(argv[1], O_RDWR, S_IRUSR | S_IWUSR);
	if (-1 == fd) {
		perror("Could not open file");
		exit(EXIT_FAILURE);
	}

	void *ptr = mmap(NULL, PAGE_SIZE, PROT_READ, MAP_SHARED, fd, 0);
	if (MAP_FAILED == ptr) {
		perror("Could not mmap file");
		exit(EXIT_FAILURE);
	}

	/* Wait for write. */
	if (false == write_goes_first) {
		sleep(2);
	}

	write(STDOUT_FILENO, ptr, PAGE_SIZE);

	munmap(ptr, 4069);

	close(fd);

	unlink(argv[1]);

	exit(EXIT_SUCCESS);
}
