C - fork and printf behavior [duplicate]

2019-03-07 09:29发布

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.

标签: c linux fork
1条回答
Anthone
2楼-- · 2019-03-07 09:46

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.

查看更多
登录 后发表回答