DEV Community

Cover image for interesting output buffer question!
IQIUM
IQIUM

Posted on

interesting output buffer question!

to be update, this is a note for me.

From jyy,I get a very interesting problem.

Sence like this,here are some code:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {
  int n = 2;
  for (int i = 0; i < n; i++) {
    fork();
    printf("Hello\n");
  }
  for (int i = 0; i < n; i++) {
    wait(NULL);
  }
}
Enter fullscreen mode Exit fullscreen mode

if we run this programe, we can get this result:

//gcc fork-printf.c && ./a.out
Hello
Hello
Hello
Hello
Hello
Hello
Enter fullscreen mode Exit fullscreen mode

there has six 'hello'

but when we use the pipe command,like this:

//gcc fork-printf.c && ./a.out | cat
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Enter fullscreen mode Exit fullscreen mode

we will get eight 'hello'.

why

In linux, when we use stdout:

for termianl: linux use line buffer, if meet character \n, linux use system calling to output all buffer.

for pipe/file: linux use full buffer, when the size of buffer is up to 4096B, (except that we call fflush(stdout)).

for conition Ⅰ,use line buffer, directly output; otherwise, for condition Ⅱ, use full buffer.

Top comments (0)