gpt4 book ai didi

C: stdout 挂起 linux 管道

转载 作者:IT王子 更新时间:2023-10-29 01:10:11 26 4
gpt4 key购买 nike

我用 C 语言编写了一个简单的 I/O 回显程序来测试一个更大的真实程序的问题。在这里,linux FD 重定向不起作用。

回显程序(又名 a.out)是:

#include <stdio.h>

int main(int argc, char **argv) {
char buff[10];
while (1) {
if (fgets(buff, 10, stdin) == NULL) break;
printf("PRINT: %s \n", buff);
}
}


在 Bash 中,我将其运行为:

$ mkfifo IN OUT
$ # this is a method to keep the pipes IN and OUT opened over time
$ while :; do read; echo Read: $REPLY >&2; sleep 1; done <OUT >IN &
$ a.out >OUT <IN &

$ echo xyz >IN

并且没有产生输出:Bash while 循环无法从 OUT 中读取。


让我们将此 a.out 与 cat 进行比较,后者按预期工作:

$ mkfifo IN OUT
$ while :; do read; echo Read: $REPLY >&2; sleep 1; done <OUT >IN &
$ cat >OUT <IN &

$ echo xyz >IN
Read: xyz

这最后一行在控制台上打印到 stderr。cat 的输出与 a.out 不同,它能够穿过 OUT 并到达 Bash while 循环,然后将其打印在安慰。
a.out 有什么问题?

最佳答案

尝试在 printf(...) 之后添加 fflush(stdout)

关于C: stdout 挂起 linux 管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12532865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com