4
votes

I have written the program which creates pipe, write a number to pipe, read it from pipe and print it to stdout. But it seems to be that fscanf see empty pipe stream, although I made fflush.

Why fprintf does not print anything?

int main() {
    int fd[2];
    pipe(fd);

    FILE* write_file = fdopen(fd[1], "w");
    FILE* read_file = fdopen(fd[0], "r");
    int x = 0;
    fprintf(write_file, "%d", 100);
    fflush(write_file);
    fscanf(read_file, "%d", &x);

    printf("%d\n", x);
}
2

2 Answers

4
votes

You have to close the writing end of the pipe, not only flush it. Otherwise the fscanf() doesn't know, if there is still data to read (more digits):

fprintf(write_file, "%d", 100);
fclose(write_file);
fscanf(read_file, "%d", &x);

Alternatively, write a blank after the digits to make fscanf() stop looking for more digits:

fprintf(write_file, "%d ", 100);
fflush(write_file);
fscanf(read_file, "%d", &x);

This should both fix your issue.

1
votes

fscanf(read_file,"%d") reads from the stream as long as it retrieves something that matches the pattern"%d", i.e. as long as no white space, non-digit, etc character is read, fscanf "waits" until the next character comes in.

Hence, fprintf(write_file, "%d\n", 100); will solve the problem, because it "terminates" the number written to the pipe, such that the subsequent fscanf will be terminated, too.