Question

I have written a basic sample program for pipe (linux - IPC) but i am getting broken pipe as output.

Below is the code :

#include<stdio.h> 

#include<unistd.h> 

#include<sys/types.h> 

#include"iostream" 

using namespace std; 

int main() 
{ 
        int fd[2],n; 
        char arr[50] = "Sample program"; 
        char buf[50] = {0}; 

        if (0 ==  pipe(fd)) 
        { 
                cout<<"Pipe created with fd[0] - "<<fd[0]<<" and fd[1] - "<<fd[1]<<endl; 
        } 

        int pid; 

        if (pid = fork() == -1) 
        { 
                cout<<"Error in FORK"<<endl; 
                exit(1); 
        } 

        if (pid == 0) 
        { 
                cout<<"In Child Process"<<endl; 

                close(fd[0]); 

                write(fd[1], arr, sizeof(arr)); 

                exit(0); 
        } 
    else{ 

                cout<<"In Parent Process"<<endl; 
                close(fd[1]); 

                n = read(fd[0], buf, sizeof(buf)); 

                cout<<"Total bytes read is : "<<n<<endl<<"Buffer is : "<<buf<<endl; 
        }         

        return 0; 
} 

Compile :

c++ pipe.cpp -g -o pipe

output:

Pipe created with fd[0] - 3 and fd[1] - 4

In Child Process

In Child Process

Broken pipe

How to solve this or what mistake i am doing?

Was it helpful?

Solution

your if condition is the problem. Change it to if ((pid = fork()) == -1)

The program shud work fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top