-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatomic_replace.c
More file actions
64 lines (61 loc) · 1.56 KB
/
atomic_replace.c
File metadata and controls
64 lines (61 loc) · 1.56 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
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
struct hdr { uint32_t magic; uint32_t version; uint64_t len; };
static int atomic_replace(const char *path, const void *buf, size_t len, uint32_t version)
{
char tmp[4096];
snprintf(tmp, sizeof tmp, "%s.tmp.%ld", path, (long)getpid());
int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
if (fd < 0) return -1;
struct hdr h;
h.magic = 0xA0A0F11E;
h.version = version;
h.len = len;
ssize_t n = write(fd, &h, sizeof h);
if (n != (ssize_t)sizeof h) goto fail;
n = write(fd, buf, len);
if (n != (ssize_t)len) goto fail;
if (fsync(fd) < 0) goto fail;
if (close(fd) < 0) goto fail;
if (rename(tmp, path) < 0) goto fail;
char dir[4096];
strncpy(dir, 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;
fail:
{
int e = errno;
close(fd);
unlink(tmp);
errno = e;
return -1;
}
}
int main(int argc, char **argv)
{
if (argc < 3) return 1;
const char *path = argv[1];
const char *msg = argv[2];
if (atomic_replace(path, msg, strlen(msg), 1) < 0) {
perror("atomic_replace");
return 1;
}
return 0;
}