/*
  Math 4970
  Bill Slough
   
  Simple pipe illustration

  A parent process writes data to a pipe; the child process reads the data
  and formats it, six characters per line.  This program is not "industrial strength";
  some error checking has been intentionally omitted for simplification.
*/

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

#define READ_END 0
#define WRITE_END 1
#define BUFFER_SIZE 6

int main() {
    /* Create some data for the parent to transmit to the child */
    char *phrases[] = {"Hello, world!", "MAT 4970", "Communication via a pipe.", NULL};
      
    /* Create the pipe */
    int fd[2];
    int result = pipe(fd);
    if (result < 0) {
	fprintf(stderr, "Pipe error\n");
	return 1;
    }
  
    /* Now create a child process and let the parent communicate with the child via this pipe */
    pid_t pid;
    pid = fork();
    if (pid > 0) {
	/* The parent should close the "read end" of the pipe */
	close(fd[READ_END]);

	/* Now the parent sends data to the child via the pipe */
	int i = 0;
	while (phrases[i] != NULL) {
	    write(fd[1], phrases[i], strlen(phrases[i]));
	    i++;
	}
    }
    else {
	/* The child should close the "write end" of the pipe */
	close(fd[WRITE_END]);

	/* The child uses a small array to store data it has read */
	char buffer[BUFFER_SIZE];

	/* How many bytes are obtained on each read() system call? */
	int n;

	/* Now the child can begin reading the data from the pipe */
	while ((n = read(fd[READ_END], buffer, BUFFER_SIZE)) > 0) {
	    write(STDOUT_FILENO, buffer, n);
	    write(STDOUT_FILENO, "\n", 1);
	}
    }
    return 0;
}
