C - fork and printf behavior [duplicate]

2019-03-07 08:59发布

问题:

This question already has an answer here:

  • Why does printf not flush after the call unless a newline is in the format string? 9 answers

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.

回答1:

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 with setbuf(), but you will have to do it as soon as your program starts (well, actually before any writes to the stream), or call fflush() 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.



标签: c linux fork