Jump to content

Parent Child communication using pipes

- - - - -

  • Please log in to reply
No replies to this topic

#1
code2learn

code2learn

    Newbie

  • Members
  • Pip
  • 9 posts
This is the simplest of program that you can get.

Here the parent communicates to child 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);  

 }  

Edited by Roger, 01 January 2011 - 06:05 PM.
removed links





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users