[Top][All Lists]

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

Re: fseek failing without fflush?

From: Eric Blake
Subject: Re: fseek failing without fflush?
Date: Tue, 09 Aug 2011 11:25:14 -0600
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv: Gecko/20110621 Fedora/3.1.11-1.fc14 Lightning/1.0b3pre Mnenhy/0.8.3 Thunderbird/3.1.11

On 08/09/2011 10:37 AM, John W. Eaton wrote:
I discovered the following surprising behavior recently when adding a
few more gnulib:: namespace tags to the Octave sources.  Eventually I
was able to generate the relatively small example attached below that
shows the same behavior and is independent of Octave.

The problem seems to be that fseek is not changing the file position
at all unless I call fflush before calling fseek.

For the underlying fd position, POSIX states:

If the most recent operation, other than ftell( ), on a given stream is fflush( 
), the file offset in the underlying open file description shall be adjusted to 
reflect the location specified by fseek( ).

Which implies that in order to guarantee that fseek() affects the underlying fd position, you must first use fflush(). Why does POSIX not require fseek() to set fd position in all cases? Because it would get in the way of implementation optimizations that exist in real life, where fseek() normally tries to seek the underlying fd to a page aligned boundary, such that the underlying fd position is distinct from the stream position, in order to allow the stream operations to operate more efficiently when actually interacting with the underlying fd.

It is the use of fflush() that tells the stream that you want the fd position to be made consistent, and to (temporarily) bypass optimizations where fd position and stream position need not match.

But for just the stream position, it seems like fseek() should work regardless of file position, and that if you don't care about syncing the underlying fd position, then ftell()/fseek(,0,SEEK_END)/ftell() should reliably tell you the end of the file without needing an fflush() in the middle, especially since there are no other input or output operations done between the fopen() and your sequence.

I'd be grateful if someone could help me understand whether this is a
bug in my code (fflush is really needed?) or if the code should be
working without having to call fflush.

I'm thinking this may be a bug in gnulib. I also know that glibc 2.14 fixed one fclose() bug in how fclose() relates to fflush(), but at the expense of introducing another, and that gnulib does not yet detect and work around that glibc bug. I'm assuming that you were testing on a glibc platform, but which version?

Eric Blake   address@hidden    +1-801-349-2682
Libvirt virtualization library http://libvirt.org

reply via email to

[Prev in Thread] Current Thread [Next in Thread]