简体   繁体   中英

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

The standard I/O functions (like printf ) are buffered , meaning output to stdout isn't printed until its buffer is full or explicitly flushed.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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