pipe in c++ not working

Here is my code for executing pipe. One end is supposed to take in a string and the other end is supposed to return string reverse. Where am I going wrong?The program executes successfully but doesn’t give the reversed string output.

#include "iostream"
#include "stdio.h"
#include "unistd.h"
#include "stdlib.h"
#include "sys/types.h"  
#include "string.h"

using namespace std;
int main()
{
int len,bufflen;
char str[80];
char buff1[80];
int mypipe[2],pid;

cout<<"Enter string.n";
fgets(str,80,stdin);
len=strlen(str);

pipe(mypipe);

if(pipe(mypipe)==-1)
{
    cout<<"Pipe creation failed.n";
    return EXIT_FAILURE;
}

pid=fork();
if(pid==-1)
{
    cout<<"fork() failed.n";
    exit(0);
}

if(pid==0)
{
    cout<<"In child process.n";
    cout<<"Reading the string...n";
    close(mypipe[0]);
    read(mypipe[1],buff1,sizeof(buff1));
    bufflen=strlen(buff1);
    for(int i=0,n=bufflen-1;i<=bufflen,n>=0;i++,n--)
        buff2[i]=buff1[n];
    cout<<"String received at the other end of the pipe.n";
    cout<<"Reversed string: "<<buff2<<endl;
    exit(0);
}

else
{
    cout<<"In parent process.n";
    cout<<"Writing the string...n";
    close(mypipe[1]);
    write(mypipe[0],str,len);
    cout<<"String passed from one end of the pipe.n";
    exit(0);
}

}


Source: c++

Leave a Reply