Tuesday, June 3, 2014

Pipes & pipes !!






All these days i was thinking , why a child process needs to get all the file descriptor of the parent process. Here i see one advantage of sharing the same . i have created a pipe and then forked a child process . So child process gets all the file descriptors(fd) that were part of parent process. Ok , Here comes the interesting part !! One process closes the read end of the pipe and other process closes write end of the pipe .. So what happens ??? we get a tunnel, one process reads and other process writes ... very good ! we have achieved inter process communication with the help of this ... I have tried to write simple C program to demonstrate the same . ####
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void main()
{
  int pipe_fd[2];
  int fd ,bytes;
  char name[32]= "I am the blogger !! \n";
  char buf[100];
memset(buf,0,sizeof(buf));
  pipe(pipe_fd);

  fd =fork();

  if(fd == 0)
  {
/*child process , close read end*/
  // while(1)
 {
    printf("Iam in child process \n");
    close(pipe_fd[0] );
    write(pipe_fd[1],name,strlen(name+1));
}
  }
  else
  {
/* Parent process , close write end*/
//while(1)
{
    printf("Iam in parent process \n");
    close(pipe_fd[1] );
    bytes = read(pipe_fd[0],buf,sizeof(buf));
    printf("bytes = %d , buf = %s \n", bytes,buf);
}
  }
Output !! # ./pipetest Iam in parent process Iam in child process bytes = 20 , buf = I am the blogger !!

No comments:

Post a Comment