This question already has an answer here:
Testing the fork function in combination with printf i found some strange behavior
For example, the code:
int main(){
if(fork()==0){
printf("TestString");
}
}
doesn't print out anything, while
int main(){
if(fork()==0) {
printf("TestString\n");
}
}
prints out TestString correctly. Why does printing a new line change the behavior? I suspect it might do something with fflush(), but i am not sure. Could i get and explanation or a link where i can read up on it? Thank you for the answer in advance.
EDITED: The explanation i am looking for is what is actually flushing and why is \n same as flushing.
On Linux (at least),
stdout
is line buffered. This means that anything you write to it will not actually appear on the screen until a'\n'
is encountered. If you don't like this behaviour you can change the buffering policy withsetbuf()
, but you will have to do it as soon as your program starts (well, actually before any writes to the stream), or callfflush()
whenever you want to flush the buffer contents, as you said.Remember that buffers are also flushed anyway when a program ends and its opened streams are automatically closed.