cfilesystemsfsyncfstat

any reason to call fsync before a call to fstat


I have a piece of legacy code that issues a call to fsync before a call to fstat to determine the filesize of the target file. (specifically the code is only accessing st_size out of the stat struct.)

Having looked at the docs, I don't believe this is a necessary call, but I wanted the expert's opinions.


Solution

  • On a correctly implemented filesystem, issuing a call to fsync or fdatasync should not affect the result of any subsequent stat/fstat/lstat call. Its only effect should be that any unflushed writes and, in the case of fsync, any modified metadata are committed to permanent storage. stat and its variants will work just fine with cached writes, regardless of whether the actual data has made to permanent storage or not.

    That said, whether fstat is needed in the piece of code that you are studying is a matter of semantics and depends on how the result of fstat is used. For example:

    So, how is the result of fstat used in your case?

    Disclaimer: there may be filesystem implementations out there, e.g. networked/distributed ones where calling fsync may update the local client metadata cache for a file. In that case that fsync call may indeed improve the reliability of the code. If that is the case, however, then you probably have worse problems than just a little performance issue...