std.fs.sync

std.fs

sync(target) -> ok, err

Hand a file's bytes to the disk

Wraps fsync(2). target is a raw fd, or a FILE* from io.open or fdopen, whose buffer is flushed first. Answers true, or nil and the errno text. A closed FILE*, or any other value, raises.

When it answers true, the kernel has handed the file's data and its metadata, the size and the mode among them, to the device, and asked the device to flush its write cache. A crash of the process or the machine after that keeps the bytes.

It does not make the file's name last. A file made or renamed since its directory was last synced can still be gone after a power loss: follow with sync_dir. A key made in place, with no rename, goes so:

local fd = assert(std.fs.open_private(path))
local f = assert(std.fs.fdopen(fd, "w"))
assert(f:write(key))
assert(std.fs.sync(f))
assert(f:close())
assert(std.fs.sync_dir(dir))

What is not promised: a device that answers a cache flush before it writes can still lose the bytes. A failed sync, "Input/output error" above all, may leave pages the kernel has already dropped, and a second sync can answer true over bytes that never reached the disk. Write the file again from its source instead.