Why does printf() not print anything before sleep()?

前端 未结 4 596
死守一世寂寞
死守一世寂寞 2020-12-05 07:45

I\'m just learning C with Kernighan and Ritchie\'s book; I\'m in the basics of the fourth chapter (functions stuff). The other day I became curious about the sleep()

4条回答
  •  一个人的身影
    2020-12-05 08:29

    printf() writes to stdout (the default output stream) which is usually line buffered. The buffer isn't flushed by the time sleep is called so nothing is displayed, when the program exits all streams are automatically flushed which is why it prints right before exiting. Printing a newline will usually cause the stream to be flushed, alternatively you could use the fflush function:

    int main(void)
    {
      printf(" I like cows.\n");
      sleep(5);
      return 0;
    }
    

    or:

    int main(void)
    {
      printf(" I like cows.");
      fflush(stdout);
      sleep(5);
      return 0;
    }
    

    If you are printing to a stream that is not line buffered, as may be the case if stdout is redirected or you are writing to a file, simply printing a newline probably won't work. In such cases you should use fflush if you want the data written immediately.

提交回复
热议问题