#include <stdio.h>
#include <unistd.h>
int main(void)
{
printf("If I had more time, \n");
write(STDOUT_FILENO, "I would have written you a shorter letter.\n", 43);
return 0;
}
I read that
I/O handling functions (
stdio
library functions) and system calls perform buffered operations for increased performance. Theprintf(3)
function usedstdio
buffer at user space. The kernel also buffers I/O so that is does not have to write to the disk on every system call. By default, when the output file is a terminal, the writes using theprintf(3)
function areline-buffered
as thestdio
uses line buffering for thestdout
i.e. when newline-character'\n'
is found the buffered is flushed to the Buffer Cache. However when is not a terminal i.e., the standard output is redirected to a disk file, the contents are only flushed when ther is no more space at the buffer (or the file stream is close). If the standard output of the program above is a terminal, then the first call toprintf
will flush its buffer to the Kernel Buffer (Buffer Cache) when it finds a newline-character'\n'
, hence, the output would be in the same order as in the above statements. However, if the output is redirected to a disk file, then thestdio
buffers would not be flushed and the contents of thewrite(2)
system call would hit the kernel buffers first, causing it to be flushed to the disk before the contents of theprintf
call.
When stdout
is a terminal
If I had more time,
I would have written you a shorter letter.
When stdout
is a disk file
I would have written you a shorter letter.
If I had more time,
But my question is that how the stdio library functions
knows whether the stdout
is directed to a terminal
or to a disk file ?
newfstatat()
is probably a Linux-specific name. The standardfstat()
should do in most systems – ilkkachu Nov 08 '22 at 19:54fstat()
(orfstatat()
), just that the system call wrapper then actually calls a (newer) kernel implementation with another name. Somewhat similarly,strace
shows a call toclone()
(with a pile of arguments) even for a simplefork()
call. – ilkkachu Nov 08 '22 at 19:59