c - 管道和 getchar()

标签 c pipe

关于 getchar() 从空文件通过管道传输时如何与 stdin 交互的困惑。

这是简单的 C 代码 test_program.c

#include <stdio.h>
int main( ) {

   int c;

   printf( "Enter a value :");
   c = getchar( );

   printf( "\nYou entered: ");
   putchar( c );
   printf( "\n");

   printf( "Enter a value :");
   c = getchar( );

   printf( "\nYou entered: ");
   putchar( c );
   printf( "\n");

   return 0;
}

好奇当我将一个空文件 (a) 通过管道传输到标准输入时会发生什么...

$ cat a | ./test_program
Enter a value :
You entered: �
Enter a value :
You entered: �

我想我会期望 test_program 阻塞,直到我实际向它提供数据。为什么它从 stdin 读取文件 a 为空的地方,并且为什么它还打印垃圾?

最佳答案

这段代码很好地解释了这一点。

#include <stdio.h>
int main(void) 
{
    int c = getchar( );
    if(c == EOF) 
        printf("EOF\n");
}

I guess I would have expected test_program to block till I actually feed it data. Why does it read from stdin where the file a is empty and why does it print garbage as well?

当您(尝试)从空流中读取数据时,您将得到一个 EOF。这就是您知道流是空的的方式。

关于c - 管道和 getchar(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58557385/

相关文章:

c - 如何通过管道将最后一个 child 的号码发送给 parent ?

node.js - NodeJs : slow req. 管道

c - 与信号量原语的进程同步

c - 代码没有输出,但正在运行。 [C]

c - Doxygen 创建表

c - 当我尝试使用 write (man 2 write) 函数时,为什么这段代码会卡住?

c - 父子进程之间发送接收Char *

c - 一行代码中的多个逻辑运算符

c - char 数组如何处理较长的字符串?

javascript - 仅当文本长度等于字母数时,如何在剪切文本时添加...?