views:

83

answers:

2

I've read in a man page that when exit() is called all streams are flushed and closed automatically. At first I was skeptical as to how this was done and whether it is truly reliable but seeing as I can't find out any more I'm going to accept that it just works — we'll see if anything blows up. Anyway, if this stream closing behavior is present in exit() is such behavior also present in the default handler for SIGINT (the interrupt signal usually triggered with Ctrl+C)? Or, would it 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 be closed properly? Or can the signal(SIG... and void onInterrupt(... lines be safely omitted?

Please restrict any replies to C, C99, and POSIX as I'm not using GNU libc. Thanks.

+4  A: 

You'll have to handle the signal if you want your buffers flushed. Otherwise the process will be terminated and the file descriptors closed without flushing the stdio buffers.

Richard Pennington
This is correct. By default, a SIGINT will terminate the process *abnornally*. Processes so terminated do not call exit() and so do not have buffers flushed.
Steve Emmerson
How do you know this?
Ollie Saunders
+5  A: 

The C99 spec 7.19.3 has a weaker guarantee:

5 If the main function returns to its original caller, or if the exit function is called, all open files are closed (hence all output streams are flushed) before program termination. Other paths to program termination, such as calling the abort function, need not close all files properly.

4 A file may be disassociated from a controlling stream by closing the file. Output streams are flushed (any unwritten buffer contents are transmitted to the host environment) before the stream is disassociated from the file.

So in C99, if it's closed then it's flushed.

The POSIX exit function has more details, in particular that whether _exit closes streams is implementation defined.

Pete Kirkham