Skip to content

Instantly share code, notes, and snippets.

@chadaustin
Last active January 11, 2018 00:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadaustin/08c76eab73c74afb280664ef9950123e to your computer and use it in GitHub Desktop.
Save chadaustin/08c76eab73c74afb280664ef9950123e to your computer and use it in GitHub Desktop.
How to atomically write a file without giving it a temporary name
#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