-1

On this C program I get output I can't understand.

#include <stdio.h>

int main()
{
    printf("Hello World\n");
    printf("%d\n", fork());
    return 0;
}

It outputs:

Hello World
5
Hello World
0

My question, is why does it print "Hello World" twice? From my understanding it would print "Hello World" then call fork().

Does fork() start from the beginning of the program?

user3440639
  • 185
  • 2
  • 12
  • 1
    "Hello world" was cached, not written. So when second process exits it prints this messsage from the output buffer too. Add `fflush(stdout)` before forking. –  Nov 06 '17 at 19:13

1 Answers1

0

If you read the manual page fork returns a value to both the parent and child. And it doesn't start from the start of the program.

Please review the manual page for fork

Ed Heal
  • 59,252
  • 17
  • 87
  • 127