fsync.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /* Emulate fsync on platforms that lack it, primarily Windows and
  2. cross-compilers like MinGW.
  3. This is derived from sqlite3 sources.
  4. https://www.sqlite.org/src/finfo?name=src/os_win.c
  5. https://www.sqlite.org/copyright.html
  6. Written by Richard W.M. Jones <rjones.at.redhat.com>
  7. Copyright (C) 2008-2021 Free Software Foundation, Inc.
  8. This library is free software; you can redistribute it and/or
  9. modify it under the terms of the GNU Lesser General Public
  10. License as published by the Free Software Foundation; either
  11. version 2.1 of the License, or (at your option) any later version.
  12. This library is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. Lesser General Public License for more details.
  16. You should have received a copy of the GNU Lesser General Public License
  17. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  18. #include <config.h>
  19. #include <unistd.h>
  20. #if defined _WIN32 && ! defined __CYGWIN__
  21. /* FlushFileBuffers */
  22. # define WIN32_LEAN_AND_MEAN
  23. # include <windows.h>
  24. # include <errno.h>
  25. /* Get _get_osfhandle. */
  26. # if GNULIB_MSVC_NOTHROW
  27. # include "msvc-nothrow.h"
  28. # else
  29. # include <io.h>
  30. # endif
  31. int
  32. fsync (int fd)
  33. {
  34. HANDLE h = (HANDLE) _get_osfhandle (fd);
  35. DWORD err;
  36. if (h == INVALID_HANDLE_VALUE)
  37. {
  38. errno = EBADF;
  39. return -1;
  40. }
  41. if (!FlushFileBuffers (h))
  42. {
  43. /* Translate some Windows errors into rough approximations of Unix
  44. * errors. MSDN is useless as usual - in this case it doesn't
  45. * document the full range of errors.
  46. */
  47. err = GetLastError ();
  48. switch (err)
  49. {
  50. case ERROR_ACCESS_DENIED:
  51. /* For a read-only handle, fsync should succeed, even though we have
  52. no way to sync the access-time changes. */
  53. return 0;
  54. /* eg. Trying to fsync a tty. */
  55. case ERROR_INVALID_HANDLE:
  56. errno = EINVAL;
  57. break;
  58. default:
  59. errno = EIO;
  60. }
  61. return -1;
  62. }
  63. return 0;
  64. }
  65. #else /* !Windows */
  66. # error "This platform lacks fsync function, and Gnulib doesn't provide a replacement. This is a bug in Gnulib."
  67. #endif /* !Windows */