logo

utils-std

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

sync.c (1909B)


  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 "../config.h" // HAS_*
  8. #include "../lib/getopt_nolong.h"
  9. #include <errno.h>
  10. #include <fcntl.h> // open, O_*
  11. #include <stdbool.h>
  12. #include <stdio.h> // fprintf
  13. #include <stdlib.h> // abort
  14. #include <string.h> // strerror
  15. #include <unistd.h> // fsync, sync, getopt, syncfs
  16. const char *argv0 = "sync";
  17. int
  18. main(int argc, char *argv[])
  19. {
  20. int err = 0;
  21. int (*sync_func)(int) = fsync;
  22. for(int c = -1; (c = getopt_nolong(argc, argv, ":df")) != -1;)
  23. {
  24. switch(c)
  25. {
  26. case 'd':
  27. sync_func = fdatasync;
  28. break;
  29. case 'f':
  30. #ifdef HAS_SYNCFS
  31. sync_func = syncfs;
  32. break;
  33. #else
  34. fprintf(stderr,
  35. "sync: error: System doesn't supports syncfs(3), continuing with error status set\n");
  36. err = 1;
  37. break;
  38. #endif
  39. case '?':
  40. GETOPT_UNKNOWN_OPT
  41. return 1;
  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: Option -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: error: 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: error: 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: error: Failed closing file-descriptor of file '%s': %s\n",
  76. argv[i],
  77. strerror(errno));
  78. return 1;
  79. }
  80. }
  81. return err;
  82. }