DEV Community

Cover image for interesting output buffer question!
IQIUM
IQIUM

Posted on

4 4

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay