printf在内部如何工作? [英] How does printf work internally?
问题描述
我很好奇printf
在Linux内部如何工作.我不明白它是如何将数据写入STDOUT
的.
I am curious as to how printf
works internally within Linux. I don't understand how it writes data to STDOUT
.
经过一番寻找内部结构的工作后,我下载了glibc
并查看了源代码:
After a bit of searching for the internals, I downloaded glibc
and took a look at the source code:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
找到这个之后,我更深入地研究了vfprintf
函数-但是该文件大约有2500行不熟悉的C代码.我正在寻找10,000英尺远的对printf如何与计算机内存配合并输出以在屏幕上显示字符的解释.
After finding this, I went deeper into the vfprintf
function - but the file is about 2500 lines of unfamiliar C code. I'm looking for an explanation from 10,000 feet of how printf works with a computer's memory and output to display characters on screen.
如果我是一段汇编代码,我该怎么做才能完成同一任务?是否取决于操作系统?
If I were a piece of assembly code what would I have to do to accomplish the same task? Is it operating system dependent?
推荐答案
我认为您正在寻找错误的图层. vfprintf
中的逻辑负责格式化其参数,并通过基础stdio函数将其写入,通常将其写入目标的FILE
对象的缓冲区中.将输出输出到文件描述符的实际逻辑(或在其他非POSIX类系统上,底层的设备/文件表示形式)可能在fwrite
,fputc
和/或某些__
前缀的内部功能(可能是__overflow
).
I think you're looking at the wrong layer. The logic in vfprintf
is responsible for formatting its arguments and writing them through the underlying stdio functions, usually into a buffer in the FILE
object it's targetting. The actual logic for getting this output to the file descriptor (or on other non-POSIX-like systems, the underlying device/file representation) is probably in fwrite
, fputc
, and/or some __
-prefixed internal functions (perhaps __overflow
).
这篇关于printf在内部如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!