Avatar of tpat
tpat
 asked on

IO Buffering...

I have a question on I/O buffering, can somebody help me out:

int main() {
        int c;
       
        printf("Hello World from PID=%d.",getpid());        
        sleep(10);
        printf("Hello Again, World! from PID=%d.\n",getpid());
        return 0;
}

the above program sleeps for 10 sec and then print out's the printf's.

Whereas, the one below print's out the statement before new line and sleeps for
10 seconds. I want to understand why is that ?

#include <stdio.h>

int main() {
        int c;
        printf("Hello World from PID=%d.\n",getpid());
        sleep(10);
        printf("Hello Again, World! from PID=%d.\n",getpid());
        return 0;
}

Thanks
CLinux OS Dev

Avatar of undefined
Last Comment
Duncan Roe

8/22/2022 - Mon
stachenov

Console output (to a screen) is usually line-buffered, meaning that a line is output when you finish it, meaning that the "\n" is the key here. Note that this is usually not true when redirecting output into a file - you should fflush(stdout) if you want to see data appearing in that file immediately, regardless of newlines.
stachenov

By the way, it's all platform-dependent too. I just tested it in Windows and it prints the first line right away regardless of flushing. On Linux, it prints it only if there is a newline or if I fflush(stdout) after the first printf().
ASKER CERTIFIED SOLUTION
Duncan Roe

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Your help has saved me hundreds of hours of internet surfing.
fblack61