0

I have the following code

    int main ( int argc, char *argv[] ){

         printf("This is parents pid %d", getpid());
         for(int i=0;i<5;i++) // loop will run n times (n=5){ 
             if(fork() == 0) { 
                 printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid()); 
                 exit(0); 
        } 
    } 

         for(int i=0;i<5;i++) // loop will run n times (n=5) 
          wait(NULL);

}

And for some reason the output is the followingenter image description here

Why it prints five times This is parent's pid??? Also when i just add a "\n" in the first print like that

printf("This is parents pid %d\n", getpid());

THE OUTPUT CHANGES TO THAT enter image description here

Can anyone please explain that to me???

Alex Doukas
  • 29
  • 1
  • 7
  • 3
    The `\n` you add make the text to be flush to stdout. On your first code, the text is not flushed and each son flushes it when `\n` is written – Mathieu Apr 01 '20 at 14:44
  • 1
    Now run the fixed program's output through `cat` — that is, `./your-fixed-prog | cat`. This is explained at the duplicate, as well as in the accepted answer. – Jonathan Leffler Apr 01 '20 at 17:52

1 Answers1

0

The output to stdout (which is where printf writes) is by default (when it's connected to a terminal) line buffered. That means the text you print is stored temporarily in a buffer in your process. The buffer is flushed (actually written) either when you explicitly flush it (with fflush), the buffer becomes full, or when you print a newline (that's why it's called line buffered).

This buffer is copied like everything else when you fork a new child process.

What happens here is that because the stdout buffer isn't flushed before you fork the child processes, all the child process will start with a buffer that contains the output you print first thing in the main function. When the child processes prints their output, which includes the newline, all of the contents is written.

The simple solution is to add a trailing newline in the initial call to printf:

printf("This is parents pid %d\n", getpid());
//                            ^^
//   Note the newline added here
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621