fflush on closed std stream

Eric Blake ebb9@byu.net
Mon Jul 20 11:43:00 GMT 2009

Hash: SHA1

POSIX is clear that calling fclose(f), fflush(f) gives unspecified
behavior.  And in general, this is true, since FILE* are allocated by
f[d]open and fclose frees that memory.  But there is a special case of
std{in,out,err}, where the FILE object persists for the lifetime of the
program, even when the program is started with the underlying fd's
inherited as closed.

Also, POSIX states that fflush must set errno to EBADF if called on a
stream with an invalid fd, but after fclose (stdout), newlib currently
treats fflush(stdout) as success (although the fact that the program has
already done undefined behavior means that we can't claim it is wrong,
just poor QoI).

I recently ran into a problem where the m4 program, when run under cygwin
1.5, is able to successfully report fclose() failures inside an atexit()
handler.  But it is reporting that error via a generic error() method that
blindly calls fflush(stdout) prior to writing to stderr.  Fortunately,
most platforms tolerate this (particularly if you don't care about errno
or the return status after the failed fflush).  But when running the same
m4 test case under cygwin 1.7, and when coupled with the libsigsegv
library, the attempt to _flockfile the closed stdout results in a
segfault.  http://cygwin.com/ml/cygwin/2009-07/msg00655.html

This patch appears to fix the issue.  Is it safe to probe fp->_flags prior
to the _flockfile, in order to skip the lock if the stream is not
currently visiting a file?  Or do I have to approach this in some other

2009-07-18  Eric Blake  <ebb9@byu.net>

	Avoid a fault from locking a closed standard file.
	* libc/stdio/fflush.c (_fflush_r): Give up early if stream has
	been previously closed.

- --
Don't work too hard, make some time for fun as well!

Eric Blake             ebb9@byu.net
Version: GnuPG v1.4.9 (Cygwin)
Comment: Public key at home.comcast.net/~ericblake/eblake.gpg
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: newlib.patch37
URL: <http://sourceware.org/pipermail/newlib/attachments/20090720/54de1f26/attachment.ksh>

More information about the Newlib mailing list