~nabijaczleweli/voreutils

ref: 8252842e7ff74305e5642881658959dc00307d44 voreutils/cmd/sync.cpp -rw-r--r-- 1.8 KiB
8252842eнаб Add echo a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// SPDX-License-Identifier: 0BSD


#include <unistd.h>
#include <cstring>
#include <vore-file>
#include <vore-getopt>
#include <vore-optarg>


static int usage(const char * argv0) {
	std::fprintf(stderr, "usage: %s [-d|-f] [file]...\n", argv0);
	return 1;
}

static __attribute__((unused)) int syncfs(...) {
	errno = ENOSYS;
	return -1;
}


enum class file_mode : std::uint8_t { normal, just_data, whole_fs };


int main(int argc, char * const * argv) {
	auto mode = file_mode::normal;
	for(auto && [arg, _] : vore::opt::get{argc,
	                                      argv,
	                                      "df",
	                                      {{"data", no_argument, nullptr, 'd'},  //
	                                       {"file-system", no_argument, nullptr, 'f'}}})
		switch(arg) {
			case 'd':
				if(mode == file_mode::whole_fs) {
					std::fprintf(stderr, "-f excludes -d!\n");
					return usage(argv[0]);
				}
				mode = file_mode::just_data;
				break;
			case 'f':
				if(mode == file_mode::just_data) {
					std::fprintf(stderr, "-d excludes -f!\n");
					return usage(argv[0]);
				}
				mode = file_mode::whole_fs;
				break;
			default:
				return usage(argv[0]);
		}

	if(*(argv + optind)) {
		for(auto file : vore::opt::args{argv + optind}) {
			vore::file::fd<false> fd{file, O_RDONLY | O_NONBLOCK | O_CLOEXEC};
			if(fd == -1) {
				std::fprintf(stderr, "%s: couldn't open %s: %s\n", argv[0], file, std::strerror(errno));
				continue;
			}

			int err;
			switch(mode) {
				case file_mode::normal:
					err = fsync(fd);
					break;
				case file_mode::just_data:
					err = fdatasync(fd);
					break;
				case file_mode::whole_fs:
					err = syncfs((int)fd);
					break;
			}
			if (err == -1)
				std::fprintf(stderr, "%s: couldn't sync %s: %s\n", argv[0], file, std::strerror(errno));
		}
	} else
		sync();
}