Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • Are you asking why output to a file (or more generally, to a non-terminal) is buffered? Commented Dec 11, 2024 at 19:58
  • Yes, that’s correct. Why is output to a file, or more generally to a non-terminal (such as when stdout is piped or redirected), buffered by default? What are the major improvements in handling I/O operations efficiently compared to leaving it unbuffered? From my perspective, the buffered output might not be written to the file or pipe in the same order, since the operating system may decide to flush the buffers of each process in an unpredictable order. Commented Dec 11, 2024 at 20:14
  • Um, what exactly is it you're asking? You already know that output to a terminal is not buffered (actually, it's usually line buffered, but you don't see that if you print full lines) but output to a file is block buffered; and you know the buffers can be flushed with fflush() or the buffering mode changed via setvbuf(). That's the policy part and how to override it. Commented Dec 11, 2024 at 20:39
  • You also ask in the comment for the "major improvements in handling I/O operations efficiently", which to me seems to answer the question: it's about efficiency. You also mentioned using the system call (write()) instead of the library call (printf()) bypasses the buffering. That's an important point, since it implies the buffering is done in the userland library level, not at the kernel level. (Though I suppose one can argue if the C library is part of the OS or not, but it's not like the low-level OS is forcing you to that buffering.) Commented Dec 11, 2024 at 20:43
  • Given the above, I'm a bit confused as to why you'd think the result is "unexpected"? You know the system buffers your writes, and that's the result you're seeing, right? The OS (be it the kernel or library) doesn't know about your syncronization policy, and it can't reason about what that should mean regarding the result. Commented Dec 11, 2024 at 20:45