write() to stdout and printf output not interleaved?

后端 未结 5 1953
轻奢々
轻奢々 2020-11-29 07:48
#include 
#define MAXLEN 256

int main() {
  int n;
  char buf[MAXLEN];
  while((n = read(0,buf,sizeof(buf))) != 0){
    printf(\"n: %d:\",n);
    wri         


        
5条回答
  •  囚心锁ツ
    2020-11-29 08:22

    Printf is buffered.

    You can force printf to 'flush' its buffer using the fflush call:

    #include 
    #define MAXLEN 256
    
    int main() {
      int n;
      char buf[MAXLEN];
      while((n = read(0,buf,sizeof(buf))) != 0){
        printf("n: %d:",n);
        fflush(stdout); /* force it to go out */
        write(1,buf,n);
      }
      return 1;
    }
    

    In general, printf() being buffered is a good thing. Unbuffered output, particularly to visible consoles that require screen updates and such, is slow. Slow enough that an application that is printf'ing a lot can be directly slowed down by it (especially on the Windows platform; Linux and unixes are typically impacted less).

    However, printf() being buffered does bite you if you also fprintf(stderr,) - stderr is deliberately unbuffered. As a consequence, you may get your messages with some printf() missing; if you write to another FILE handle that is also associated with the terminal, and might be unbuffered, make sure you first explicitly fflush(stdout).

提交回复
热议问题