Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does fork() start from [duplicate]

Tags:

c

fork

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;
}
like image 453
Filip Spasovski Avatar asked Dec 07 '25 05:12

Filip Spasovski


1 Answers

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.

like image 67
Chris Dodd Avatar answered Dec 08 '25 18:12

Chris Dodd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!