c - 使用系统函数 read() 和 write() 时 Linux 在终端中输出的机制

标签 c unix terminal stdout

代码:

#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/

相关文章:

c++ - 我将如何在进程的内存中搜索特定字符串?

c - 从列表中删除节点中保存的字符串

linux - Git:如何列出所有试图提交的(暂存的)文件

c - Unix 域套接字错误,sendmsg : No buffer space available

linux - cat 和 more 有不同的输出

bash - 如何让 tmux 仅在 vim 未运行时应用选项?

node.js - 如何终止在本地主机 :8080 that does not exist on computer 上为旧站点提供服务的 Node 进程

c - C 中每个数据包都有 TTL 的数据包队列的最佳收集类型是什么

c - 将树附加到网格

ssh - 无需再次登录即可复制 SSH 终端窗口