/* Copyright (c)1994-2000 Begemot Computer Associates. All rights reserved.
 * See the file COPYRIGHT for details of redistribution and use. */

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

# include <begemot.h>
# include "cdefs.h"
# include "util.h"

RCSID("$Id: mmap_test.c 417 2000-03-04 08:04:07Z hbb $")

# define FD 7

int
main(int argc, char *argv[])
{
	pid_t pid;
	int fd, i;
	struct stat statb;
	caddr_t c;
	int *p;

	if(fstat(FD, &statb) == 0) {
		/*
		 * Child process
		 */
		fd = FD;
		c = mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
		if((int)c == -1)
			panic("child mmap: %s", strerror(errno));
		p = (int *)c;

		for(i = 0; i < 12; i++) {
			printf("C(%d) ", *p);
			fflush(stdout);
			sleep(1);
		}
		printf("\n");
		return 0;
	}
	if((fd = open("gulp", O_RDWR|O_CREAT)) < 0)
		panic("gulp: %s", strerror(errno));
	if(ftruncate(fd, 4))
		panic("ftruncate: %s", strerror(errno));
	if(fd != FD)
		(void)dup2(fd, FD);

	if((pid = fork()) < 0)
		panic("fork: %s", strerror(errno));

	if(pid == 0) {
		execl("mmap_test", "mmap_test", NULL);
		_exit(17);
	}
	c = mmap(NULL, 4, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
	if((int)c == -1)
		panic("parent mmap: %s", strerror(errno));
	p = (int *)c;
	*p = 0;
	printf("P(%d) ", *p);
	fflush(stdout);
	sleep(3);
	*p = 1;
	printf("P(%d) ", *p);
	fflush(stdout);
	sleep(3);
	*p = 0;
	printf("P(%d) ", *p);
	fflush(stdout);
	sleep(3);

	return 0;
}
