title: Why does write() print before printf() in output redirection?
body: <p>So I know <code>printf()</code> is higher level than <code>write()</code> and ends up using <code>write()</code>. <code>Printf()</code> is buffered and <code>write()</code> makes system calls. </p>
  
  <p>Example 1, if I were to run a program with <code>printf()</code> before <code>write()</code> then it would output the value of <code>printf()</code> before the value of <code>write()</code>.</p>
  
  <p>Example 2, if I were to run the same program and have it go through output redirection into a file, the value of <code>write()</code> outputs before <code>printf()</code>.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  
  int main()
  {
      printf("This is a printf test\n");
      write(STDOUT_FILENO, "This is a write test\n", 21);
      return 0;
  }
  </code></pre>
  
  <p>I don't understand what is happening here. In example 1, is the program waiting for <code>printf()</code>s output before running <code>write()</code>? In example 2, is the program redirecting the first output that is ready? And because <code>write()</code> is lower level, and does not need to buffer like <code>printf()</code> then it is printed first?</p>