user1733212
user1733212

Reputation: 111

What is the functional difference between sync()/fsync() and std::ofstream.flush()?

Background: I'm working with VxWorks for the first time in my life, and I'm having to translate some inherited code so that it will work in VxWorks.

Problem & Solution: The codebase calls sync(). There's no definition for sync() in VxWorks headers (at least, not the ones I have). I have fsync(), which requires a file descriptor to work. The function which calls sync() is writing to the file with a ofstream object before calling sync... and there's no obvious way to recover a file descriptor from an ofstream object.

After an embarrassingly long time rooting around for options, I discover the ofstream::flush() function, which ought to work for what I'm trying to do.

However, in my rooting it was pointed out to me that ofstream::flush() and sync/fsync are associated with different things (IIUC, the C library and the operating system, respectively). That suggests that ofstream::flush() won't achieve quite the same thing that sync() or fsync() will.

Can someone lay out the difference for me? My understanding is still far too fuzzy to be relied upon in future.


Followup: The original code appends a std::endl to the stream and calls sync. My understanding is that appending endl will have the effect of flush(). If the original code has both, that suggests to me either that

  1. the code is redundant
  2. flush() and sync()/fsync() are both required because they do similar but not identical things.

which is it?

Upvotes: 0

Views: 1027

Answers (1)

Jean-Jacques
Jean-Jacques

Reputation: 51

If you know the device name being used for the file system, it would be easy to develop a stub fonction that would perform the sync() operation on that device:

fd = open(...);
fsync(fd);
close(fd);

Ideally the code could parse all open fd to the file system and do an ioctl() operation, by passing the command FIOFLUSH or FIOSYNC.

For example:

status = ioctl(fd, FIOSYNC, 0); /* see definition in ioLib.h */

You can have a look at iosFdShow() code for going through all file descriptor.

Upvotes: 1

Related Questions