2

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?

Vitaly Isaev
  • 5,392
  • 6
  • 45
  • 64
  • 1
    Can't you just do what the manual says `O_SYNC` effectively does: `i.e., as though each write(2) was followed by a call to fsync(2)` – kaylum Jun 04 '20 at 12:32
  • 1
    Can you not just call `fsync` or `fdatasync` on the descriptor after the `write` call? – alani Jun 04 '20 at 12:32
  • Thanks @kaylum, @alaniwi , to clarify my question, I'm debuggind a service with high IOPS consumption. It's configured to use async writes only, but according to statistics, it looks like it's use all disk bandwidth just like if it wrote synchronously. So I'm trying to use `strace` to find out what's going on. – Vitaly Isaev Jun 04 '20 at 12:49

1 Answers1

2

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

  1. read and store the current flags

    int flags = fcntl(fd, F_GETFL);
    
  2. set new flags that include O_SYNC

    int result = fcntl(fd, F_SETFL, flags | O_SYNC);
    
  3. perform the write

  4. 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.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • If there is a difference between the effects of using O_SYNC (when opening the file) or using fsync() (wafter ich write to the file)? – Silicomancer Sep 08 '21 at 13:34
  • @Silicomancer, if you specify `O_SYNC` when opening the file, then the system behaves approximately as if every write to the file is followed by an `fsync()` for the file. It cannot be *exactly* the same because separating the syncing from the writing affords the opportunity for one to succeed despite the other failing. – John Bollinger Sep 08 '21 at 16:38