Such flags as O_DIRECT
, O_SYNC
, O_DSYNC
can be used to specify synchronous / asynchronous IO at the time when descriptor is created (create
syscall). But is it possible to use this flags for distinct write
(or similar) syscalls in order to make some of them synchronous?
Advertisement
Answer
is it possible to use this flags for distinct write (or similar) syscalls in order to make some of them synchronous?
No, O_SYNC
is meaningful only for the purposes it is documented for: open()
and related syscalls. Data transfer system calls such as write()
do not accept flags. Whether writes are synchronous is a property of the open file description, not of individual data transfer operations.
You can, however, follow up individual write()
calls with fsync()
calls on the same file descriptor to ensure that the data are dispatched to the physical device.
Alternatively, you can use fcntl()
to modify the file’s flags after opening it. You would
read and store the current flags
int flags = fcntl(fd, F_GETFL);
set new flags that include
O_SYNC
int result = fcntl(fd, F_SETFL, flags | O_SYNC);
perform the
write
restore the original flags
result = fcntl(fd, F_SETFL, flags);
(Note: function call results need to be checked for error conditions. Such checks are omitted from the above summary for clarity.)
Unless you absolutely need the write
call itself to be synchronous, however, it is much easier to leave the flags alone and just call fsync()
where needed. That’s what it’s for, after all.