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.

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

AWS Security LIVE!

Hosted by security experts, AWS Security LIVE! showcases AWS Partners tackling real-world security challenges. Join live and get your security questions answered.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️