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.
Both fprintf (stdout,"") and printf ("") statements are used to write to NetSim's log file (LogFile.txt). printf ("") sends formatted output to stdout.
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.
The printf has written text to the stdout buffer, which is finally written in each branch of the fork via the exit call.
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!");
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With