logo

utils-std

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

sync.c (1923B)


  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: error: System doesn't supports syncfs(3), continuing with error status set\n");
  34. err = 1;
  35. break;
  36. #endif
  37. case '?':
  38. fprintf(stderr,
  39. "sync: error: Unrecognized option '-%c', continuing with error status set\n",
  40. optopt);
  41. err = 1;
  42. break;
  43. default:
  44. abort();
  45. }
  46. }
  47. argc -= optind;
  48. argv += optind;
  49. if(argc == 0)
  50. {
  51. #ifdef HAS_SYNCFS
  52. if(sync_func == syncfs) fprintf(stderr, "sync: warning: Option -f passed without arguments\n");
  53. #endif
  54. sync();
  55. return err;
  56. }
  57. for(int i = 0; i < argc; i++)
  58. {
  59. int fd = open(argv[i], O_RDONLY);
  60. if(fd < 0)
  61. {
  62. fprintf(stderr, "sync: error: Failed opening file '%s': %s\n", argv[i], strerror(errno));
  63. return 1;
  64. }
  65. if(sync_func(fd) < 0)
  66. {
  67. fprintf(stderr,
  68. "sync: error: Failed synchronizing changes related to file '%s': %s\n",
  69. argv[i],
  70. strerror(errno));
  71. return 1;
  72. }
  73. if(close(fd) < 0)
  74. {
  75. fprintf(stderr,
  76. "sync: error: Failed closing file-descriptor of file '%s': %s\n",
  77. argv[i],
  78. strerror(errno));
  79. return 1;
  80. }
  81. }
  82. return err;
  83. }