简体   繁体   English

为什么fprintf和fscanf不适用于管道

[英]Why fprintf and fscanf does not work with pipe

I have written the program which creates pipe, write a number to pipe, read it from pipe and print it to stdout. 我编写了创建管道的程序,将数字写入管道,从管道读取并将其打印到stdout。 But it seems to be that fscanf see empty pipe stream, although I made fflush. 但似乎fscanf看到空管流,虽然我做了fflush。

Why fprintf does not print anything? 为什么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);
}

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): 否则fscanf()不知道,如果还有数据需要读取(更多数字):

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: 或者,在数字后面写一个空白以使fscanf()停止寻找更多数字:

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

This should both fix your issue. 这应该都可以解决您的问题。

fscanf(read_file,"%d") reads from the stream as long as it retrieves something that matches the pattern "%d" , ie as long as no white space, non-digit, etc character is read, fscanf "waits" until the next character comes in. fscanf(read_file,"%d")从流中读取,只要它检索到与模式"%d"匹配的内容,即只要没有读取空格,非数字等字符, fscanf “等待”直到下一个角色进来了。

Hence, fprintf(write_file, "%d\\n", 100); 因此, 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. 将解决问题,因为它“终止”写入管道的数字,这样后续的fscanf也将被终止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM