-2

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.

IamSneaky
  • 23
  • 7
  • Yes you need to use `fflush(stdout)` or use newline just what you did. – ani627 Sep 25 '14 at 07:52
  • printf is buffered, and the content of the buffer is displayed when a newline '\n' character is encountered. Flushing means to clear the content of the buffer associated with printf. I tested this code and it prints "TestString" in both the cases. – Abhishek Choubey Sep 25 '14 at 07:56

1 Answers1

0

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.

SukkoPera
  • 621
  • 4
  • 8