12/28/10

Parent-Child Communication Using Pipes in UNIX

This is the simplest of program that you can get.

Here the parent-child communicates over a pipe.

NOTE:
if the child wants to communicate to the parent then it will have to closes(fd[0]) and parent will closes(fd[1]).

this will only work UBUNTU, LINUX(RedHat) , Solaris, FreeBDS etc all UNIX VERSIONS. DONT TRY to use it on any compiler like gcc,turbo c, etc...

Send data from Parent to Child over a pipe:




#include <apue.h>  
#include <sys/types>  
#include <sys/wait.h>  

int main(void)  
 {  
   int   n;  
   int   fd[2];  
   pid_t  pid;  
   char  data[]="Hello world";  
   char  line[MAXLINE];  

   pid = fork();

   if (pipe(fd) < 0)  
     printf("pipe error");  
   if (pid < 0) {  
     printf("fork error");  
   } else if (pid > 0) {    /* parent */  
     close(fd[0]);  
     write(fd[1], data, strlen(data));  
   } else {        /* child */  
     close(fd[1]);  
     n = read(fd[0], line, MAXLINE);  
     write(STDOUT_FILENO, line, n);  
   }  
   exit(0);  
 }  

SHARE THIS POST: