Otniel-Bogdan Mercea
Otniel-Bogdan Mercea

Reputation: 405

Linux pipes in C

I have the following code:

#include<stdio.h>

FILE *f,*stream1,*stream2,*stream3,*stream4;

int main()
{
    int pfd[2];
    int pfd1[2];
    int pfd2[2];
    int pid1;
    int pid2;

    pipe(pfd);
    pipe(pfd1);
    pipe(pfd2);

    f=fopen("date","r");
    pid1=fork();


    if(pid1==0){

        close(pfd[1]);

        stream2=fdopen(pfd[0],"r");

        char c;
        int rd=fread(&c,sizeof(char),1,stream2);
        while(rd!=0){
            printf("%c",c);
            rd=fread(&c,sizeof(char),1,stream2);
        }
        close(pfd[0]);
        exit(0);

    }

    pid2=fork();

    if(pid2==0){

        printf("second process\n");
        exit(0);

    }
    if(pid1>0&&pid2>0){
        close(pfd[0]);
        stream1=fdopen(pfd[1],"w");
        while(!feof(f)){
            char c;
            fscanf(f,"%c",&c);
            if(feof(f)) break;
            fwrite(&c,sizeof(char),1,stream1);
        }
        close(pfd[1]);
        exit(0);
    }
}

This code takes some input from a file and displays it in child1. The problem is that whenever I want to close pfd[1] in the parent process, the output in child1 (pid1) doesn't show up. Why is this happening? If I don't close pfd[1] it goes normally.

Edit: I solve it .The problem was that i used fread,fwrite instead of read and write. With this in place everything runs as i wanted.

Upvotes: 0

Views: 224

Answers (1)

Martin Rosenau
Martin Rosenau

Reputation: 18493

There are two problems:

1) You are using fdopen and fwrite instead of writing to the pipe using write.

This is possible however fwrite will buffer the data before calling write internally.

When you call fclose(stream1) the fclose function will first write all buffered data using write() and then call close(pfd[1]).

However if you call close(pfd[1]) directly the buffered data is not written to the pipe.

2) When a program finishes child processes are typically also killed.

Don't leave the main function until all child processes created using fork also have finished. (It does not matter if you use return or exit()).

Use the waitpid or the wait4 function to wait for a child process to finish.

I compiled the program on my computer: Only when fixing both problems I get the desired result.

Upvotes: 1

Related Questions