(How) is it true that the write() syscall stores data in the kernel?

117 Views Asked by At

In this stackoverflow question answer it is said that after sys call returns the data is in kernel. But isn't data output to the display and no more in kernel? Can someone explain in more detail? I can't comment in mentioned article because I don't have enough reputation.

From: what is the different of using fflush(stdout) and not using it

When the syscall returns, the data is in your kernel. But modern operating systems buffer this data as well. This is used to reduce the number of disk writes, reduce latency and other things. This buffer is completely independent of the FILE buffer inside your program.

2

There are 2 best solutions below

1
Eric Postpischil On BEST ANSWER

For currently active interactive devices, such as displays, the kernel will quickly display the data.1 The text you refer to in the other answer is about data being written to storage devices. The kernel may hold that data briefly, to combine it with other write operations. What is important here is that your program no longer has responsibility for the data. Even if your process exits or crashes after executing a fflush, the kernel will still write the data to storage. (The operating system can still crash, and data can be lost that way.)

Footnote

1 Depending on the operating system, it may be possible to stop terminal output by various means such as pressing Control-S, or a window may be currently covered by other windows and hence is not being updated.

0
Caleb On

But isn't data output to the display and no more in kernel?

As far as the OS is concerned, the display is just another file; printf() is basically just a version of fprintf() that assumes the output should go to stdout, i.e. the standard output stream. That stream normally is sent to the display, but in many operating systems you an also redirect it to a file or to the input of some other program.

What the answer you referred to is saying is that when you write to a file (or stream), the data you send is buffered by the printf() (or fprintf()) command, and calling fflush() triggers a context switch that moves the data from the buffer that it's in and into the kernel. From there, you don't have any control over what happens to it — it might be sent immediately to its destination or held in another buffer, but either way it'll eventually get to where it's meant to be.