简体   繁体   English

使用系统功能read()和write()时终端中linux输出的机制

[英]Mechanism for linux output in terminal when using system function read() & write()

Code: 码:

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

My question: How does it work? 我的问题:如何运作?

(why buffer text output before n_read?) (为什么在n_read之前缓冲文本输出?)

The standard I/O functions (like printf ) are buffered , meaning output to stdout isn't printed until its buffer is full or explicitly flushed. 标准I / O函数(如printf )被缓冲 ,这意味着直到其缓冲区已满或显式刷新后,才输出到stdout

On the other hand, writing directly to the output file descriptor is not buffered and is written directly. 另一方面,直接写入输出文件描述符的操作不会缓冲,而是直接写入。

What you have here is you mixing direct and buffered output, and the buffered output isn't actually written until the program exits and the buffer is flushed. 您所拥有的是将直接输出和缓冲输出混合在一起,直到程序退出并且刷新缓冲区后,缓冲输出才真正写入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM