Pipe.c

From Organic Design wiki
Revision as of 22:04, 20 March 2007 by Rob (talk | contribs) (added foo code)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
  1. include <errno.h>
  2. include <unistd.h>
  3. include <stdlib.h>
  4. include <stdio.h>
  5. include <fcntl.h>
  1. 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;

}