I'm following this guide about fork()
but something isn't clear for me.
Both processes will start their execution at the next statement following the fork() call. In this case, both processes will start their execution at the assignment statement as shown below:
According to this sentence, this script
printf("before ");
fork();
printf("after ");
should print this: (Because child process will start from printf("after")
)
before after after
but it is printing this instead:
before after before after
So did the child process start from the 1st line of the file? Can you tell me what's wrong with my code? Did I misunderstood that sentence?
EDIT
Script compiled and executed on OS X
When you create a new process, it 'inherits' all the variables of the original process - thus all the buffers as well. Since "before" wasn't flushed yet and is still in the buffer, the child process will as well contain this string in the buffer and print it. Therefore you have to call fflush(stdout);
before forking the process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With