# Safe File Update (atomic)



## Olaf (Jan 5, 2011)

What is the recommended way for atomic (complete) file data updates in FreeBSD?

The non-atomic variant is like:

```
// old state
int fd = open("", O_CREAT | O_TRUNC | O_WRONLY)
write(fd, ...); // 0+ times
fsync(fd); // optional
close(fd);
// new state
```

Note this is more about kernal internals then userspace.


----------



## adihodos (Jan 11, 2011)

Look at the man page for open(), the O_DIRECT flag.


----------



## Olaf (Jan 13, 2011)

Eh, no, that's no the right flag.


----------



## Fred (Jan 16, 2011)

Under Linux (and I believe most other Un*xen), the recommended way is to write to another file in the same partition, and then use the fact that rename(2) or link(2) guarantee that when the destination argument already exists, it will always point to either the old file, or the new one, even if the system crashes in between.


----------



## Olaf (Jan 16, 2011)

I know. I hoped FreeBSD / ZFS had a better way.


----------

