2

I understand the working of write() call wherein it writes the data only to kernel's buffers which is later written to disk by kernel after sorting the data optimally.

Calling fsync() on file descriptor makes sure that data is written to disk as soon as it's posted in the kernel's buffer. My question is, whether fsync() should be called before write() or after write() call. I've read couple of books on the topic, looked on the internal as well but couldn't find a satisfactory answer.

2 Answers2

0

your understanding of write is kinda wrong. after calling the write system call, it queues the data into kernel's buffer then it flushes out the data into the opened file descriptor whether it is an opened file or a socket.

  • No offence but your understanding is wrong, what you said happens in standard I/O. write call directly writes to the kernel's buffer. Refer to man page of write. – Neeraj Sharma Aug 28 '22 at 09:12
  • if the kernel write buffer is full, it needs to queue them. FIFO rules IF the kernel write buffer is full but if not, it directly writes to it – Antoine Zayyat Oct 22 '22 at 20:43
  • Kernel flushes the data to the disk in following conditions: If dirty buffer has aged pass the specified threshold or if buffer memory has shrunk below the specified threshold. Kernel buffer is never full, before it gets full, the data is already written to the disk. – Neeraj Sharma Oct 23 '22 at 10:11
  • if at Kernel compiation time, the user compiles the Kernel with a configuration file that shows a small Kernel stack, that would definitely cause problems in the Kernel including buffering in it. – Antoine Zayyat Oct 23 '22 at 12:15
0
  1. fsync should be called after the write system call. It flushes the file data buffers and the metadata to the physical device.

  2. Alternatively, you can use the O_SYNC flag in the open system call for the file and get the same result for each subsequent write call.

kjohri
  • 1,166
  • 11
  • 10
  • Correct answer but I won't call O_SYNC as an alternative to fsync() because according to "Linux System Programming by Robert Love": Linux kernel has implemented O_SYNC a bit more efficiently which results in slightly worse user and kernel times for write operations. If the file is big, then the cost is huge. – Neeraj Sharma Aug 12 '22 at 18:35