// This code sample is execerpted from P. Wang's Intro to ANSI C on UNIX
// and partially modified for  CSC345 class
#include <stream.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

#define MAXCHARS 30
#define CHUNK 10

main(int argc, char *argv[])
{
  int fds[2]; // an array of 2 file descriptors fpr a pipe
  char buffer[MAXCHARS];
  int i, pid, status;

  pipe(fds);			// create a pipe
  pid = fork();
  if (pid == 0)			// child process
    {
      close (fds[1]);		// close a write descriptor
      while (( i = read(fds[0], buffer, CHUNK)) != 0) 
	{
	  buffer[i] = '\0';
	  cout << i << " characters \"" <<  buffer << "\" received by child" << endl;
	}
      _exit(0);
    }

  else {			// parent
    close(fds[0]);
    write(fds[1], "Hello CSC345 OS class", sizeof("Hello CSC345 OS class"));
    write(fds[1], "this is a message from parent process", sizeof("this is a message from parent process"));
    close (fds[1]);
    wait(&status);
    cout << "a child has finished" << endl;
  }
}
