Zsombi
Zsombi

Reputation: 84

Linux C - child process thinks the pipe is empty

I have a problem with this homework exercise. I am learning the Linux C so I am a beginner.

Now the exercise is simple: I have to create a child process. Now the parent process needs to read a text file (e.g. a.txt) and sends through a pipe. The child process reads from pipe and prints the content of the pipe to the terminal. But I don't understand that the child process doesn't read the pipe because it thinks the pipe is empty.

I post the code what I did so far:

#include "myinclude.h" //a separate file which contains all needed headers to run the program.

#define MERET 80

int main(int argc,char *argv[]){

    int pfd[2];
    int status;
    char buffer[MERET];
    pid_t pid;
    FILE *fp1,*fp2;
    if(argc != 2){
        printf("Nincs eleg argumentum");
    }
    if(pipe(pfd) < 0){
        syserr("pipe");
    }
    if((pid = fork()) < 0){
        syserr("fork");
    }
    if(pid == 0){
        close(pfd[1]);
        if ((fp1 = fdopen (pfd[0],"r")) <0){
                    syserr("fdopen");
            }
        printf("mukodsz");
        while(fgets(buffer,MERET,fp1) != NULL){//something here is not good 
            printf("%s",buffer);
            fprintf(stdout,"Siker");
        }
        close(pfd[0]);
        exit(0);
    }
    close(pfd[0]);
    if ((fp1 = fdopen (pfd[1],"w")) == NULL){
        syserr("fdopen");
    }
    if((fp2 = fopen(argv[1],"r")) < 0){
        syserr("fopen");
    }
    while(fgets(buffer,MERET,fp2) != NULL){
        fprintf(fp1,"%s",buffer);
        //fprintf(stdout,"Siker\n");
    }
    close(pfd[1]);
    wait(&status);
    //fprintf(stdout,"Siker");
    exit(0);
}

In my language "siker" means Success. I used it to debug the program but while loop of the child process is not printing anything.

Upvotes: 0

Views: 179

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119857

When you fdopen. you must fclose.

If you close the original file descriptor instead, all not-yet-written data in buffers associated with the FILE* get lost.

Upvotes: 1

Related Questions