3

So as far as i know fork creates a duplicate of the process it's called from but it also copy's it's program counter so it continues from the line after it's called but why is this code printing hello world twice when it's before the fork

#include <stdio.h>
#include <sys/wait.h>
int main()
{
    printf("Hello World");

    fork();

    wait(NULL);
    return 0;
}

1 Answers1

3

printf doesn't actually print -- it actually just puts data into a buffer to be printed later. It will actually be printed when the buffer gets flushed, which can happen in a variety of ways.

In your case, the buffer flush doesn't happen until after the fork, so both the parent and the child have a copy of the string to be printed in the buffer when they fork, and both end up printing it.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • But IMO is the implementation error. Fork should duplicate the process variables but not the OS or I/O internal buffers. Otherwise it makes the behaviour of the forked processes undefined – 0___________ Apr 03 '18 at 00:36
  • Its perfectly well defined -- it duplicates at the OS interface level. So everything above that (including the standard C library) is duplicated. That's why the POSIX standard adds lots of extra requirements onto the standard C library; so exactly what happens there is defined. – Chris Dodd Apr 03 '18 at 01:48