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

/*
 * Programa que cria um pipe simples entre
 * um processo pai e o seu filho:
 * o pai le do terminal e escreve essa mensagem
 * no pipe e o filho le.
 *
 * Jose Rogado
 */


#define BUFSIZE 512

main(int argc, char *argv[])
{
   pid_t pid;
   int count;
   int pipeID[2];
   char buffer[BUFSIZE];

   printf("Parent process %d\n", getpid());
   // open a pipe
   if (pipe(pipeID) < 0) {
      perror("pipe");
      exit(1);
   }

   /* fork another process */
   pid = fork();
   if (pid < 0) {	 /* error occurred */
	fprintf(stderr, "Fork Failed");
	exit(-1);
   } else if (pid == 0) {
	 /* child process */
	while (1) {
	  bzero(buffer, sizeof(buffer));

	  if (read(pipeID[0], buffer, sizeof(buffer))< 0)
	    break;
	  printf("Child process %d Received: %s\n", getpid(), buffer);
	}
	printf("child exiting\n");
	exit(0);
   } else {
	 /* parent process */
     printf("Parent process created child %d\n", pid);
     while(1) {
       // loop reading input to send to child
       count = getline(buffer, sizeof(buffer));
       if (count < 0)
	 break;
       if (write(pipeID[1], buffer, count) < 0)
	 break;
       // printf("Parent wrote %d bytes\n", count);
     }
     kill (pid, SIGKILL);
     printf ("End of File\n");
     exit(0);
     }
}

int getline (char *buffer, int bufsize)
{
   int count = 0;
   char *p;

   bzero(buffer, bufsize);
   p = fgets(buffer, bufsize, stdin);

   if (p)
	count = strlen(p);
   else
     count = -1;

   //   printf("Sending %d: %s", count, buffer);
   return count;
}




