How does printf work internally? [duplicate]

我们两清 提交于 2019-12-18 19:09:45

问题


I am curious as to how printf works internally within Linux. I don't understand how it writes data to STDOUT.

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;
}

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?


回答1:


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



来源:https://stackoverflow.com/questions/18279908/how-does-printf-work-internally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!