Printf flush on program exit

I am interested to know how the flash printf() function works when a program exits.

Take the following code:

 int main(int ac, char **av) { printf("Hi"); return 0; } 

In this case, how does printf() manage to flush its buffer to stdout ?

I think it depends on the platform, so let Linux.

It can be implemented using gcc __attribute__((dtor)) , but then the standard library will be compiler dependent. I guess this is not how it works.

Any explanation or links to documentation are appreciated. Thanks.

+11
source share
4 answers

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

See description.

+10
source

When a program crashes, the exit function always performed a clean shutdown of the standard I / O library, which leads to the painting of all buffered output.

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 , the process will be terminated immediately, IO will not be cleared.

+3
source

Just to expand trofanjoe's answer:

exit causes normal program termination. Atexit functions are called in the reverse order of registration, open files are discarded, open threads are closed, and control returns to the environment.

and

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

+3
source

From man stdio on my machine here (highlighted by me) that runs RHEL 5.8:

Then the file can be reopened by the same or different program execution and its contents corrected or changed (if it can be moved at the beginning). If the main function returns to its original calling object or exit function (3), all open files are closed (therefore, all output streams are reset) before the program terminates. Other ways to terminate a program, such as interrupting (3), do not worry about closing files.

+1
source

Source: https://habr.com/ru/post/1239580/


All Articles