logo

utils-std

Collection of commonly available Unix tools git clone https://anongit.hacktivis.me/git/utils-std.git

sync.c (1866B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #define _GNU_SOURCE // syncfs
  6. #define _XOPEN_SOURCE 700 // sync
  7. #include <errno.h>
  8. #include <fcntl.h> // open, O_*
  9. #include <stdbool.h>
  10. #include <stdio.h> // fprintf
  11. #include <stdlib.h> // abort
  12. #include <string.h> // strerror
  13. #include <unistd.h> // fsync, sync, getopt, syncfs
  14. int
  15. main(int argc, char *argv[])
  16. {
  17. int err = 0;
  18. int (*sync_func)(int) = fsync;
  19. int c = -1;
  20. while((c = getopt(argc, argv, ":df")) != -1)
  21. {
  22. switch(c)
  23. {
  24. case 'd':
  25. sync_func = fdatasync;
  26. break;
  27. case 'f':
  28. #ifdef HAS_SYNCFS
  29. sync_func = syncfs;
  30. break;
  31. #else
  32. fprintf(stderr,
  33. "sync: System doesn't supports syncfs(3), continuing with error status set\n");
  34. err = 1;
  35. break;
  36. #endif
  37. case '?':
  38. fprintf(
  39. stderr, "sync: Unrecognized option '-%c', continuing with error status set\n", optopt);
  40. err = 1;
  41. break;
  42. default:
  43. abort();
  44. }
  45. }
  46. argc -= optind;
  47. argv += optind;
  48. if(argc == 0)
  49. {
  50. #ifdef HAS_SYNCFS
  51. if(sync_func == syncfs) fprintf(stderr, "sync: Warning -f passed without arguments\n");
  52. #endif
  53. sync();
  54. return err;
  55. }
  56. for(int i = 0; i < argc; i++)
  57. {
  58. int fd = open(argv[i], O_RDONLY);
  59. if(fd < 0)
  60. {
  61. fprintf(stderr, "sync: Failed opening file '%s': %s\n", argv[i], strerror(errno));
  62. return 1;
  63. }
  64. if(sync_func(fd) < 0)
  65. {
  66. fprintf(stderr,
  67. "sync: Failed synchronizing changes related to file '%s': %s\n",
  68. argv[i],
  69. strerror(errno));
  70. return 1;
  71. }
  72. if(close(fd) < 0)
  73. {
  74. fprintf(stderr,
  75. "sync: Failed closing file-descriptor of file '%s': %s\n",
  76. argv[i],
  77. strerror(errno));
  78. return 1;
  79. }
  80. }
  81. return err;
  82. }