开发者

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

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开发者_StackOverflow中文版 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜