Add sync to file_helper (#2343)

This commit is contained in:
espkk 2023-01-15 15:33:40 +02:00 committed by GitHub
parent 5a63426d1c
commit f29f369a12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 27 additions and 2 deletions

View File

@ -90,6 +90,14 @@ SPDLOG_INLINE void file_helper::flush()
} }
} }
SPDLOG_INLINE void file_helper::sync()
{
if(!os::fsync(fd_))
{
throw_spdlog_ex("Failed to fsync file " + os::filename_to_str(filename_), errno);
}
}
SPDLOG_INLINE void file_helper::close() SPDLOG_INLINE void file_helper::close()
{ {
if (fd_ != nullptr) if (fd_ != nullptr)

View File

@ -26,6 +26,7 @@ public:
void open(const filename_t &fname, bool truncate = false); void open(const filename_t &fname, bool truncate = false);
void reopen(bool truncate); void reopen(bool truncate);
void flush(); void flush();
void sync();
void close(); void close();
void write(const memory_buf_t &buf); void write(const memory_buf_t &buf);
size_t size() const; size_t size() const;

View File

@ -23,9 +23,10 @@
#ifdef _WIN32 #ifdef _WIN32
# include <io.h> // _get_osfhandle and _isatty support # include <io.h> // for _get_osfhandle, _isatty, _fileno
# include <process.h> // _get_pid support # include <process.h> // for _get_pid
# include <spdlog/details/windows_include.h> # include <spdlog/details/windows_include.h>
# include <fileapi.h> // for FlushFileBuffers
# ifdef __MINGW32__ # ifdef __MINGW32__
# include <share.h> # include <share.h>
@ -601,6 +602,17 @@ std::string SPDLOG_INLINE getenv(const char *field)
#endif #endif
} }
// Do fsync by FILE descriptor
// Return true on success
SPDLOG_INLINE bool fsync(FILE *fd)
{
#ifdef _WIN32
return FlushFileBuffers(reinterpret_cast<HANDLE>(_get_osfhandle(_fileno(fd)))) != 0;
#else
return ::fsync(fileno(fd)) == 0;
#endif
}
} // namespace os } // namespace os
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog

View File

@ -109,6 +109,10 @@ SPDLOG_API bool create_dir(const filename_t &path);
// return empty string if field not found // return empty string if field not found
SPDLOG_API std::string getenv(const char *field); SPDLOG_API std::string getenv(const char *field);
// Do fsync by FILE descriptor
// Return true on success
SPDLOG_API bool fsync(FILE * fd);
} // namespace os } // namespace os
} // namespace details } // namespace details
} // namespace spdlog } // namespace spdlog