Pipe.c

From Organic Design wiki
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>

#define BIG 4096000

int main(int argc, char **argv, char **envp )
{
int pfds[2];
int status;
char buffer[BIG];
int pid;
int i,r,l;

	printf("Begin\n");

  if(pipe(pfds) == -1)
   exit(errno);
  
  printf("pipe(): %d %d\n", pfds[0], pfds[1]);
	
	putenv("FOO=foo was set by the parent");
	
	
  if((pid = fork()) == -1 )
  {
		printf("fork(): failed\n");
		exit(1);
  }
  else if(pid)
  {
	printf("fork() pid %d\n", pid);
    //parent
  	close(pfds[1]);
    wait(&status);

	printf("wait() returned with status %d\n",status);
      
	while( i = read(pfds[0], &buffer, BIG ) ) {
		printf("read(): fetched %d bytes\n", i);
      printf("%s\n", buffer);
		}

		char *env;
		env = getenv("FOO");
		printf("Parent: FOO=%s\n", env);

  }
  else
  {
    //child
    int fd = open("/dev/null", O_RDWR, 0);
    dup2(fd, 0);
    close(pfds[0]);
		dup2(pfds[1], 1);

		// set env
		putenv("FOO=foo was set by the child");
				
    execl("hello.sh", "hello.sh" );
		// should never get to here
    _Exit(0);
  }
  return 0;
}