tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: fflush(NULL) and mem streams (fmemopen(), open_*memstream())



On Sat 12 Jan 2019 at 08:03:38 +0700, Robert Elz wrote:
> An issue was recently dealt with wrt the POSIX spec, in respose to
> a question whether fflush(NULL) is required to flush memory streams,
> or only ones backed by files.

When I saw this, my first reaction was "What does it even *mean* to
flush a memory stream!? They don't have a buffer, they *are* the
buffer!" I think the C++ stringstream that I was thinking of doesn't
have a concept of flushing, for instance (it has an accessor function
for the resulting string instead).

The buffer is generally used to prevent doing too many expensive
operations, such as system calls. Reflecting a bit more on the POSIX
description of open_memstream(), I came to the conclusion that the
expensive operation here may be the updating of *bufp and *sizep (which
may include reallocing the buffer), and the adding of a NUL (not null)
character just past the end. These are described to be only valid after
a call to fflush() or fclose().

Then my thoughts came to unbuffered streams.  However POSIX doesn't seem
to describe much about unbufferend streams. It just says "When a stream
is "unbuffered", bytes are intended to appear from the source or at the
destination as soon as possible;" but not if this is supposed to be
equivalent to calling fflush(). So it is unclear to me if you still need
to call fflush() on a memory stream to have *bufp and *sizep updated.

[...]
> The arguments against fflush(NULL) affecting memory streams, are
> that it can reduce the amount of bookkeeping needed (such streams
> need not be linked into a list somewhere so they can be found, and
> then removed again later),

There still needs to be such a list of non-memory streams anyway, so I
don't see the advantage there.

> that fflush(NULL) is usually performed only as a process is exiting,
> to make sure all data is written to the files, which is irrelevant for
> mem streams (which vanish anyway),

But for memory streams, fflush() (or fclose()) is also needed if you
want to look at the resulting memory buffer, so fflush() is probably
called more often. That makes this a weak argument as well.

> If there are any arguments, one way or the other, I would be happy
> to pass them along.

I think my reasoning above goes in the direction that fflush(NULL)
*should* also affect memory streams.

> kre
-Olaf.
-- 
___ Olaf 'Rhialto' Seibert  -- "What good is a Ring of Power
\X/ rhialto/at/falu.nl      -- if you're unable...to Speak." - Agent Elrond

Attachment: signature.asc
Description: PGP signature



Home | Main Index | Thread Index | Old Index