From f29f369a12c701db27e816c6762e914863e8e951 Mon Sep 17 00:00:00 2001 From: espkk Date: Sun, 15 Jan 2023 15:33:40 +0200 Subject: [PATCH] Add sync to file_helper (#2343) --- include/spdlog/details/file_helper-inl.h | 8 ++++++++ include/spdlog/details/file_helper.h | 1 + include/spdlog/details/os-inl.h | 16 ++++++++++++++-- include/spdlog/details/os.h | 4 ++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/include/spdlog/details/file_helper-inl.h b/include/spdlog/details/file_helper-inl.h index d4528711..3c45d8c0 100644 --- a/include/spdlog/details/file_helper-inl.h +++ b/include/spdlog/details/file_helper-inl.h @@ -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() { if (fd_ != nullptr) diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h index 0f5988b9..f42a5eb1 100644 --- a/include/spdlog/details/file_helper.h +++ b/include/spdlog/details/file_helper.h @@ -26,6 +26,7 @@ public: void open(const filename_t &fname, bool truncate = false); void reopen(bool truncate); void flush(); + void sync(); void close(); void write(const memory_buf_t &buf); size_t size() const; diff --git a/include/spdlog/details/os-inl.h b/include/spdlog/details/os-inl.h index 2ac8cc3f..42acf3fe 100644 --- a/include/spdlog/details/os-inl.h +++ b/include/spdlog/details/os-inl.h @@ -23,9 +23,10 @@ #ifdef _WIN32 -# include // _get_osfhandle and _isatty support -# include // _get_pid support +# include // for _get_osfhandle, _isatty, _fileno +# include // for _get_pid # include +# include // for FlushFileBuffers # ifdef __MINGW32__ # include @@ -601,6 +602,17 @@ std::string SPDLOG_INLINE getenv(const char *field) #endif } +// Do fsync by FILE descriptor +// Return true on success +SPDLOG_INLINE bool fsync(FILE *fd) +{ +#ifdef _WIN32 + return FlushFileBuffers(reinterpret_cast(_get_osfhandle(_fileno(fd)))) != 0; +#else + return ::fsync(fileno(fd)) == 0; +#endif +} + } // namespace os } // namespace details } // namespace spdlog diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h index b154bc47..742482d0 100644 --- a/include/spdlog/details/os.h +++ b/include/spdlog/details/os.h @@ -109,6 +109,10 @@ SPDLOG_API bool create_dir(const filename_t &path); // return empty string if field not found 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 details } // namespace spdlog