-1

I am working with forks at the moment, and I came accross a strange dehavior while trying to get a process printing 10 "." each second and second one printing 5 "*" every couple of seconds.

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char const *argv[]) {
  int pid = fork();

  //parent
  if (pid > 0){
    for(int i = 0; i < 5; i++){
      printf("\n*\n");
      sleep(2);
    }
  }
  //child
  else{
    for(int i = 0; i < 10; i++){
      printf("\n.\n");
      sleep(1);
    }
  }
  return 0;
}

With this code I get the following output:

*

.

.

*

.

.

*

.

.

*

.

.

*

.

.

Which is what I expected but if I remove the \n from the printf functions like this

  printf("*");

Then I get this output:

*****..........

Is there any explanation as why the order of the output is different ?

KerDam
  • 421
  • 4
  • 9

2 Answers2

0

Multiple processes writing to the same STDOUT will only push data to the the file descriptor when it is flushed. Newlines flush, as does the process exiting. So when newlines are printed, each line is flushed as printed. But if not, the output for each is buffered until it exits, and then it is all written at once.

Doug
  • 644
  • 1
  • 6
  • 22
0

Output can be cached for some time before actually getting written out. A \n in the output stream generally triggers the current output stream to get flushed. Without \n, it looks like the output was not flushed until the program exited, then everything was written out.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31