-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs_txn.c
More file actions
94 lines (90 loc) · 2.21 KB
/
Copy pathfs_txn.c
File metadata and controls
94 lines (90 loc) · 2.21 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
typedef struct {
const char *path;
const char *tmp;
const char *data;
} txn_entry_t;
static int write_temp(const char *tmp, const char *data)
{
int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
if (fd < 0) return -1;
size_t len = strlen(data);
ssize_t n = write(fd, data, len);
if (n != (ssize_t)len) {
int e = errno;
close(fd);
unlink(tmp);
errno = e;
return -1;
}
if (fsync(fd) < 0) {
int e = errno;
close(fd);
unlink(tmp);
errno = e;
return -1;
}
if (close(fd) < 0) {
int e = errno;
unlink(tmp);
errno = e;
return -1;
}
return 0;
}
static int txn_commit(txn_entry_t *entries, size_t n)
{
for (size_t i = 0; i < n; i++) {
if (write_temp(entries[i].tmp, entries[i].data) < 0) return -1;
}
for (size_t i = 0; i < n; i++) {
if (rename(entries[i].tmp, entries[i].path) < 0) return -1;
}
for (size_t i = 0; i < n; i++) {
char dir[4096];
strncpy(dir, entries[i].path, sizeof dir);
dir[sizeof dir - 1] = 0;
char *slash = strrchr(dir, '/');
if (slash) {
*slash = 0;
int dfd = open(dir, O_RDONLY | O_DIRECTORY);
if (dfd >= 0) {
fsync(dfd);
close(dfd);
}
}
}
return 0;
}
int main(int argc, char **argv)
{
if (argc < 3) {
fprintf(stderr, "usage: %s file1 file2\n", argv[0]);
return 1;
}
char tmp1[4096], tmp2[4096];
snprintf(tmp1, sizeof tmp1, "%s.tmp.%ld", argv[1], (long)getpid());
snprintf(tmp2, sizeof tmp2, "%s.tmp.%ld", argv[2], (long)getpid());
txn_entry_t e[2];
e[0].path = argv[1];
e[0].tmp = tmp1;
e[0].data = "file1 contents\n";
e[1].path = argv[2];
e[1].tmp = tmp2;
e[1].data = "file2 contents\n";
if (txn_commit(e, 2) < 0) {
perror("txn_commit");
return 1;
}
printf("committed\n");
return 0;
}