Last active
January 11, 2018 00:30
-
-
Save chadaustin/08c76eab73c74afb280664ef9950123e to your computer and use it in GitHub Desktop.
How to atomically write a file without giving it a temporary name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <stdio.h> | |
// Can't get O_TMPFILE to work for some reason. | |
#ifndef __O_TMPFILE | |
# define __O_TMPFILE (020000000 | __O_DIRECTORY) | |
#endif | |
int main() { | |
int fd = open(".", __O_TMPFILE | O_RDWR, 0600); | |
if (fd == -1) { | |
perror("open failed"); | |
return 1; | |
} | |
if (12 != write(fd, "hello world\n", 12)) { | |
perror("write failed"); | |
return 1; | |
} | |
char buf[800]; | |
sprintf(buf, "/proc/self/fd/%d", fd); | |
if (-1 == linkat(AT_FDCWD, buf, AT_FDCWD, "helloworld.txt", AT_SYMLINK_FOLLOW)) { | |
perror("linkat failed"); | |
return 1; | |
} | |
// note that linkat does not allow replacing existing files, so this is less | |
// useful than it seems :/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment