Question

Is there a need to explicitly flush output streams before calling abort() to avoid loss of output?

As I understand, with stderr there is no buffering, so calling abort after output to stderr/cerr should be ok. How about stdout/cout, or files that I open?

PS. I am working in Linux environment (if it matters).

Était-ce utile?

La solution

Yes, it's needed, but no, it may not be possible. If you're aborting from an async-signal context, calling fflush invokes undefined behavior. And in general, if the reason for calling abort is that you've detected inconsistent state in your program, there's a risk that stdio state is also corrupted, and that calling fflush is therefore unsafe.

In general, you should use exit(1) if you're terminating due to a condition that your program simply can't handle, and use abort() (without fflush) only when you have detected that your program invoked undefined behavior already,

Some more details:

The C standard allows an implementation to flush stdio streams as part of abort (C11 7.22.4.1:):

Whether open streams with unwritten buffered data are flushed, open streams are closed, or temporary files are removed is implementation-defined.

However, this does not remove the requirement that abort work if called from a signal handler. Since, from a practical standpoint, it's usually impossible to flush buffers if abort is being called from a signal handler that interrupted stdio code that has the buffer in an inconsistent state, any implementation that attempts to use this allowance is likely to be buggy.

The current version of the Linux man page for abort incorrectly states:

If the abort() function causes process termination, all open streams are closed and flushed.

A more correct statement of the current behavior would be that flushing is attempted but may fail or corrupt your data. This bug is presently in the process of being fixed in glibc (maybe the fix was already committed...?) according to this thread:

http://www.sourceware.org/ml/libc-alpha/2013-05/msg00207.html

Autres conseils

Stdout is buffered and so are the file you open with ofstream for example. You have to explicitly flush them using the flush manipulator

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top