More you share, more you have!!!

More you share, more you have!!!

C program for interprocess communication using pipe system call

pipe-c-program

Question:

Write an interprocess communication program using unnamed pipe. Process A accepts a character string and Process B inverses the string. Pipe is used to establish communication between A and B processes using C++. 

Answer: 

Program using unnamed pipe:

#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
int ret_val;
int fd[2];
char buff[100]="";
char string1[100]="";
cout<<"\nEnter the msg= ";
cin>>string1;
ret_val = pipe(fd);                
if (ret_val != 0)            
{
  cout<<"Unable to create a pipe";
  exit(1);
}
if (fork() == 0)
{
   close(fd[0]);
   ret_val = write(fd[1],string1,strlen(string1));
   if (ret_val != strlen(string1))
{
      cout<<"Write did not return expected value\n";
      exit(2);
   }
}
else
{
   close(fd[1]);
   ret_val = read(fd[0],buff,strlen(string1));
   if (ret_val != strlen(string1))
   {
   cout<<"Read did not return expected value\n";
   exit(3);
   }
   cout<<"Parent read "<<buff<<" from the child program\n";
}
exit(0);
}



Output:




adi@bravo:~/osd/osd$ g++ mypipe.cpp 
adi@bravo:~/osd/osd$ ./a.out 
.Enter the msg= hello 
Parent read hello from the child program 

Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment