Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the print to stdout not happen when using fprintf?

I have this code:

#include <stdio.h>
#include <unistd.h>
int main()
{
        while(1)
        {
                fprintf(stdout,"hello-out");
                fprintf(stderr,"hello-err");
                sleep(1);
        }
        return 0;
}

The output is hello-err hello-err hello-err hello-err hello-err hello-err at 1 sec intervals. I want to know why hello-out never gets printed.

like image 953
insane Avatar asked Jul 03 '12 16:07

insane


People also ask

What is the difference between fprintf (stdout) and printf ()?

Both fprintf (stdout,"") and printf ("") statements are used to write to NetSim's log file (LogFile.txt). printf ("") sends formatted output to stdout.

What does printf () do in NetSim?

printf ("") sends formatted output to stdout. printf () is customized in NetSim to print to the stdout which normally writes to LogFile.txt. The definition for printf ("") can be found in main.h file towards the end of the file.

Where does printf write the text?

The printf has written text to the stdout buffer, which is finally written in each branch of the fork via the exit call.

Is it possible to call fflush () from the stdout output?

You can call fflush, but sometimes, depending on how the caching works, simply ending the output with a newline is sufficient. So try changing fprintf(stdout, "STARTED!");


2 Answers

You need to fflush stdout because usually stdout is line buffered and you don't issue a new line character in your program.

            fprintf(stdout,"hello-out");
            fflush(stdout);

stderr is not fully buffered by default so you don't need to fflush it.

like image 116
ouah Avatar answered Sep 26 '22 06:09

ouah


stdout is line-buffered by default, meaning that the buffer will be flushed at every end-of-line ('\n'). stderr is unbuffured, so every character is sent automatically without the need to flush.

You can confirm this by placing a \n at the end of the stdout output. That way both lines will be printed at 1 second intervals.

like image 36
Naps62 Avatar answered Sep 23 '22 06:09

Naps62