printf flush at program exit

前端 未结 4 1095
萌比男神i
萌比男神i 2020-12-16 17:54

I\'m interested in knowing how the printf() function\'s flush works when the program exits.

Let\'s take the following code:

int main(int         


        
相关标签:
4条回答
  • 2020-12-16 17:55

    When the program exits normally, the exit function has always performed a clean shutdown of the standard I/O library, this causes all buffered output data to be flushed.

    Returning an integer value from the main function is equivalent to calling exit with the same value.So, return 0 has the same effect with exit(0)

    If _Exit or _exit was called, the process will be terminated immediately, the IO won't be flushed.

    0 讨论(0)
  • 2020-12-16 18:05

    The C runtime will register atexit() handlers to flush standard buffers when exit() is called.

    See this explanation.

    0 讨论(0)
  • 2020-12-16 18:12

    Just to expand trofanjoe's response:

    exit causes normal program termination. atexit functions are called in reverse order of registration, open files are flushed, open streams are closed, and control is returned to the environment.

    and

    Within main, return expr is equivalent to exit(expr). exit has the advantage that it can be called from other functions

    0 讨论(0)
  • 2020-12-16 18:13

    From man stdio on my machine here (emphasis added), whic runs RHEL 5.8:

    A file may be subsequently reopened, by the same or another program execution, and its contents reclaimed or modified (if it can be repositioned at the start). If the main function returns to its original caller, or the exit(3) function is called, all open files are closed (hence all output streams are flushed) before program termination. Other methods of program termination, such as abort(3) do not bother about closing files properly.

    0 讨论(0)
提交回复
热议问题