C/Unix Strange behaviour while using system calls and printf

早过忘川 提交于 2019-12-02 08:50:09

<stdio.h> functions like printf are buffered. Output functions will call the write(2) syscall only from time to time, usually output functions like printf etc... are going only into the internal FILE buffer.

The stdout is line-buffered when outputting to a terminal (see isatty(3)). So if a printf format string ends with \n the write will occur.

You could add a fflush(stdout); or fflush(NULL); call before your while loop.

See fflush(3) and setvbuf(3)

If you don't flush stdout (either with a \n in printf format string, or explicitly thru fflush or fclose) the buffer is flushed only at the end of main (thru some implicit atexit(3) ...)

So what is happening to you is that (without the \n) data stays in the stdout buffer, and is actually written (by the write(2) inside stdio library) only at the exit of your program.

Read advanced linux programming.

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