15

Here's a very basic question I have. In my professor's lecture slide, there is a example I dont really get.

She wrote:

printf("u"); 
write(STDOUT_FILENO, "m", 1); 
printf("d\n");

...and she said the out put of this code would be:

mud

I don't get it. So if anyone understand why this happens, please explain to me.

Reference this question:

http://lagoon.cs.umd.edu/216/Lectures/lect17.pdf

(in the second last slide page.)

Allan Jiang
  • 11,063
  • 27
  • 104
  • 165

2 Answers2

23

write is a system call -- it is implemented by the interface between user mode (where programs like yours run) and the operating system kernel (which handles the actual writing to disk when bytes are written to a file).

printf is a C standard library function -- it is implemented by library code loaded into your user mode program.

The C standard library output functions buffer their output, by default until end-of-line is reached. When the buffer is full or terminated with a newline, it is written to the file via a call to write from the library implementation.

Therefore, the output via printf is not sent to the operating system write immediately. In your example, you buffer the letter 'u', then immediately write the letter 'm', then append "d\n" to the buffer and the standard library makes the call write(STDOUT_FILENO, "ud\n");

Heath Hunnicutt
  • 18,667
  • 3
  • 39
  • 62
10

By default, stdout is line-buffered; it isn't flushed to the output until it encounters a newline character (or until the buffer fills up).

So the "u" sits in the buffer until the "d\n" is received. But the write bypasses this buffer.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • I would not say that write "subverts" anything. The buffer is intact and working properly. More accurately, write is a system call and printf is a library function. – Heath Hunnicutt Dec 14 '11 at 18:31
  • 2
    stdout is *not* line buffered by default. *if* stdout is associated with a tty, then it is line buffered by default. If stdout is a regular file or a pipe (or really anything other than a tty) it will be block buffered by default. – William Pursell Dec 14 '11 at 19:34
  • @WilliamPursell: technically, if stdout _can be determined_ to not be an interactive device, it may be block buffered instead of line buffered. – ninjalj Dec 14 '11 at 21:09