作者:安小辰 | 来源:互联网 | 2023-05-17 05:50
Iamwritinganapplicationwhichfirstreceivesdatafromaunixpipeline,andthenpromptingtheu
I am writing an application which first receives data from a unix pipeline, and then prompting the user for input. What I cannot seem to figure out is why the input from the pipeline does not seem to close properly before prompting the user for input. It feels like I'm missing something very elementary here.
我正在编写一个应用程序,它首先从unix管道接收数据,然后提示用户输入。我似乎无法弄清楚为什么在提示用户输入之前管道的输入似乎没有正确关闭。感觉我在这里缺少一些非常基本的东西。
I have tried all examples for flushing stdin presented here without success. This also seems potentially relevant, but I have not managed to extract any relevant answers.
我已经尝试了所有用于刷新stdin的例子而没有成功。这似乎也有可能相关,但我还没有设法提取任何相关的答案。
#include
#include
#define BUFSZ 1024
int main(void) {
char *buf = calloc(BUFSZ, sizeof(char));
while(fgets(buf, BUFSZ, stdin)) { printf("Pipe input: %s", buf); }
printf("Enter input: ");
fgets(buf, BUFSZ, stdin);
printf("User input: %s", buf);
free(buf);
return 0;
}
Example usage and output:
用法和输出示例:
$ cat testdata2 | ./a.out
Pipe input: testdata testdata
Pipe input: testdata testdata2
Pipe input: testdata testdata3
Pipe input: testdata testdata4
Pipe input: testdata testdata5
Pipe input: testdata testdata6
Pipe input: testdata testdata7
Enter input: User input: testdata testdata7
$
How can it be that the second fgets() (intended for keyboard input) never touches the buffer?
怎么可能第二个fgets()(用于键盘输入)从不接触缓冲区?
This MCVE has been compiled tested on OSX and Linux with identical results.
该MCVE已经在OSX和Linux上进行了编译测试,结果相同。
1 个解决方案