#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
using namespace std;

int main(){
	cout<<"======================================="<<endl;
	cout<<"      LINUX IPC: THE ONE-WAY PIPE      "<<endl;
	cout<<"=======================================\n"<<endl;
	int fd[2];
	if(pipe(fd)==-1){
		cerr<<"FATAL ERROR: Failed to create the pipe!"<<endl;
		return 1;
	}
	cout<<"[SYSTEM] Pipe succesfully created in Kernel Space."<<endl;
	pid_t process_id=fork();
	if(process_id<0){
		cerr<<"FATAL ERROR: fork() failed!"<<endl;
		return 1;
	}
	else if(process_id==0){
		close(fd[0]);
		const char* secret_message="Hello Father! I found the hidden treasure int the new memory space!";
		cout<<"  ->[CHILD] Pouring secret message into the pipe..."<<endl;
		write(fd[1], secret_message, strlen(secret_message)+1);
		close(fd[1]);
		cout<<"  ->[CHILD] Message sent. Terminating."<<endl;
		return 0;
	}
	else{
		close(fd[1]);
		cout<<"[PARENT] Waiting by the pipe for a message..."<<endl;
		char buffer[200];
		read(fd[0], buffer, sizeof(buffer));
		cout<<"[PARENT] I received the message from the pipe!"<<endl;
		cout<<"[PARENT] The message says: \""<<buffer<<"\""<<endl;
		close(fd[0]);
		wait(NULL);
		cout<<"[PARENT] Child has been safely reaped. Shutting down."<<endl;
	}
	return 0;
}
