Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are open streams automatically flushed and closed on SIGINT in C?

Tags:

c

posix

signals

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.

like image 419
Ollie Saunders Avatar asked Dec 14 '22 00:12

Ollie Saunders


1 Answers

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.

like image 194
Pete Kirkham Avatar answered Dec 28 '22 23:12

Pete Kirkham