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

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

int main()
{
	pid_t  pid;
	int status;
	int pipeID[2];
	char buffer[64];
	char message[] = "Ola eu sou o teu pai, porta-te bem !!";
	printf("Parent process %d\n", getpid());

	/* open a pipe */
	if (pipe(pipeID) < 0) {
		perror("pipe");
	}
	/* fork another process */
	pid = fork();
	if (pid < 0) { /* error occurred */
		fprintf(stderr, "Fork Failed");
		exit(-1);
	} else if (pid == 0) { /* child process */
		/* Child reads pipe */
		read(pipeID[0], buffer, sizeof(buffer));
		printf("Process %d Received: %s\n", getpid(), buffer);
		exit(0);
	} else { /* parent process */
	  	printf("Parent process created child %d\n", pid);
		/* parent writes message to pipe */
		write(pipeID[1], message, sizeof(message));
		wait(&status);
		exit(0);
	}
}
