Open threads are automatically flushed and closed on SIGINT in C?

I read the man page that when calling exit() all threads are automatically cleared and closed. At first I was skeptical about how this was done and whether it was really reliable, but, seeing that I canโ€™t find out more, I agree that it just works - weโ€™ll see that something explodes. In any case, if this behavior of closing a stream is present in exit() , is this behavior also present in the default handler for SIGINT (the interrupt signal is usually triggered using Ctrl + C)? Or, it would be necessary to do something like this:

 #include <signal.h> #include <stdlib.h> void onInterrupt(int dummy) { exit(0); } int main() { signal(SIGINT, onInterrupt); FILE *file = fopen("file", "a"); for (;;) { fprintf(file, "bleh"); } } 

to get file to close properly? Or is it safe to skip the lines of signal(SIG... and void onInterrupt(... ?

Please limit any answers to C, C99, and POSIX since I do not use GNU libc. Thanks.

+4
source share
2 answers

Specification 7.19.3 C99 has a weaker warranty:

5 If the main function returns to the original caller or if the exit function is called, all open files are closed (therefore, all output streams are cleared) until the program ends. Other ways to exit the program, such as calling the interrupt function, do not need to close all files properly.

4 The file can be disconnected from the control stream by closing the file. Output streams (the contents of any unwritten buffer are transferred to the host environment) until the stream is disconnected from the file.

So, on C99, if it's closed, it blushed.

The POSIX exit function contains more detailed information, in particular, that if _exit closes threads, this implementation is defined.

+7
source

You will need to process the signal if you want your buffers to turn red. Otherwise, the process will be completed, and the file descriptors will be closed without cleaning the stdio buffers.

+6
source

All Articles