为什么 fprintf 和 fscanf 不能与管道一起使用

Nik*_*rov 5 c unix

我已经编写了创建管道的程序,将一个数字写入管道,从管道中读取它并将其打印到标准输出。但似乎 fscanf 看到空的管道流,尽管我做了 fflush。

为什么 fprintf 不打印任何内容?

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);
}
Run Code Online (Sandbox Code Playgroud)

Ctx*_*Ctx 5

您必须关闭管道的写入端,而不仅仅是冲洗它。否则fscanf(),不知道是否仍有数据要读取(更多数字):

fprintf(write_file, "%d", 100);
fclose(write_file);
fscanf(read_file, "%d", &x);
Run Code Online (Sandbox Code Playgroud)

或者,在数字后面写一个空格以停止fscanf()寻找更多数字:

fprintf(write_file, "%d ", 100);
fflush(write_file);
fscanf(read_file, "%d", &x);
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题。