sync.c (1923B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #define _GNU_SOURCE // syncfs
- #define _XOPEN_SOURCE 700 // sync
- #include <errno.h>
- #include <fcntl.h> // open, O_*
- #include <stdbool.h>
- #include <stdio.h> // fprintf
- #include <stdlib.h> // abort
- #include <string.h> // strerror
- #include <unistd.h> // fsync, sync, getopt, syncfs
- int
- main(int argc, char *argv[])
- {
- int err = 0;
- int (*sync_func)(int) = fsync;
- int c = -1;
- while((c = getopt(argc, argv, ":df")) != -1)
- {
- switch(c)
- {
- case 'd':
- sync_func = fdatasync;
- break;
- case 'f':
- #ifdef HAS_SYNCFS
- sync_func = syncfs;
- break;
- #else
- fprintf(stderr,
- "sync: error: System doesn't supports syncfs(3), continuing with error status set\n");
- err = 1;
- break;
- #endif
- case '?':
- fprintf(stderr,
- "sync: error: Unrecognized option '-%c', continuing with error status set\n",
- optopt);
- err = 1;
- break;
- default:
- abort();
- }
- }
- argc -= optind;
- argv += optind;
- if(argc == 0)
- {
- #ifdef HAS_SYNCFS
- if(sync_func == syncfs) fprintf(stderr, "sync: warning: Option -f passed without arguments\n");
- #endif
- sync();
- return err;
- }
- for(int i = 0; i < argc; i++)
- {
- int fd = open(argv[i], O_RDONLY);
- if(fd < 0)
- {
- fprintf(stderr, "sync: error: Failed opening file '%s': %s\n", argv[i], strerror(errno));
- return 1;
- }
- if(sync_func(fd) < 0)
- {
- fprintf(stderr,
- "sync: error: Failed synchronizing changes related to file '%s': %s\n",
- argv[i],
- strerror(errno));
- return 1;
- }
- if(close(fd) < 0)
- {
- fprintf(stderr,
- "sync: error: Failed closing file-descriptor of file '%s': %s\n",
- argv[i],
- strerror(errno));
- return 1;
- }
- }
- return err;
- }