Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

c - Why does write() print before printf() in output redirection?

So I know printf() is higher level than write() and ends up using write(). Printf() is buffered and write() makes system calls.

Example 1, if I were to run a program with printf() before write() then it would output the value of printf() before the value of write().

Example 2, if I were to run the same program and have it go through output redirection into a file, the value of write() outputs before printf().

#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("This is a printf test
");
    write(STDOUT_FILENO, "This is a write test
", 21);
    return 0;
}

I don't understand what is happening here. In example 1, is the program waiting for printf()s output before running write()? In example 2, is the program redirecting the first output that is ready? And because write() is lower level, and does not need to buffer like printf() then it is printed first?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You answered your own question.

printf is buffered and write is not.

For output to a terminal, the C stdio system has a feature that it flushes the buffers whenever it sees a newline ' '. For more about stdio buffering look at the documentation for setvbuf.

But when output is to a file to increase speed the stdio system does not flush the buffer. That is why write output appears first.

Here is some of the strace output from running on my Linux system:

fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f7880b41000
write(1, "This is a printf test ", 22) = 22
write(1, "This is a write test ", 22) = 22

The fstat is where the stdio system detects the type of output file descriptor 1 is connected to. I believe it looks at st_mode and sees that it is a character device. A disk file would be a block device. The mmap is the memory allocation for the stdio buffer, which is 4K. Then the output is written.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...