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


int main(int argc, char *argv[]) {
	int file;
	pid_t pid;
	//make fifo
	mknod("aPipe", S_IFIFO|0666, 0); 
	//fork storing the returned id
	pid = fork();
	//handle a form error
	if(pid == -1) {
		fprintf(stderr, "Error forking.\n");
		return EXIT_FAILURE;
	} 
	//handle the child
	if(pid == 0) {
		char buffer[101];
		printf("Child %d waiting for readers...\n", getpid());
		if((file = open("aPipe", O_WRONLY)) == -1) {
			fprintf(stderr, "Error opening fifo for child.\n");
			return EXIT_FAILURE;
		}
		printf("got a reader--type some stuff\n");
		while(fgets(buffer, 100, stdin) != NULL) {
			write(file, buffer, strlen(buffer)+1);
		}
		close(file);
		printf("Child %d exiting\n", getpid());
	//handle the parent
	} else { 
		char buffer[101];
		int bytes;
		
		printf("Parent waiting for writers...\n");
		if((file = open("aPipe", O_RDONLY)) == -1) {
			fprintf(stderr, "Error opening fifo for parent.\n");
			return EXIT_FAILURE;
		}
		
		printf("got a writer:\n");
		while((bytes = read(file, buffer, 101)) != 0) {
			if(bytes == -1) {
				fprintf(stderr, "Error reading from fifo.\n");
				return EXIT_FAILURE;
			}
				printf("parent: read %i bytes: %s\n",  bytes, buffer);
		}
		//make sure child has ended
		waitpid(pid);
		//cleanup
		close(file);
		remove("aPipe");
		printf("Parent exiting.\n");
	}
}
