/* Sample of creating a pipe and using it within
   a single process.

   This example creates a pipe, then writes a bunch of stuff 
   to the pipe and closes the writing end.

   Then it reads everything from the pipe and prints to STDOUT.

*/

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

/* here is the actual data sent to the pipe: */

char data[] = "0123456789abcdefghijklmnopqrstuvwxyz";


int main(int argc, char **argv) {
  int fds[2];
  char buff[10];
  int n;

  /* attempt to create a pipe  */
  if (pipe(fds)<0) {
	perror("Fatal Error");
	exit(1);
  }


  /* write the string to the pipe */
  if (write(fds[1],data,sizeof(data))<0) {
	perror("Error writing the pipe");
	exit(1);
  }
  
  /* close the writing end of the pipe */
  close(fds[1]);

  /* now read everything we can from the pipe,
	 and write it to stdout */

  while ( (n=read(fds[0],buff,10))>0) {

	write(STDOUT_FILENO,"\nChunk: ",8);
	write(STDOUT_FILENO,buff,n);
	write(STDOUT_FILENO,"\n",1);
  }
  if (n<0) {
	perror("Error reading");
	exit(1);
  }

  /* close the reading end of the pipe */
  close(fds[0]);

  return(0);
}

