代码:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
char buf[BUFSIZ];
int n;
while((n = read(0, buf, BUFSIZ)) > 0 && printf("1:%d ", n))
{
printf("2:%d ", n);
write(1, buf, n);
}
return 0;
}
pupu(my input)
pupu(output)
popopo(my input)
popopo(output)
1:5 2:5 1:7 2:7(output)
我的问题:它是如何工作的?
(为什么在n_read之前缓冲文本输出?)
最佳答案
标准 I/O 函数(例如 printf
)是缓冲的,这意味着在缓冲区已满之前不会打印到 stdout
的输出或显式刷新。
另一方面,直接写入输出文件描述符不被缓冲,而是直接写入。
这里混合了直接输出和缓冲输出,并且直到程序退出并且刷新缓冲区后才真正写入缓冲输出。
关于c - 使用系统函数 read() 和 write() 时 Linux 在终端中输出的机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16759546/