1

If the call to fork() is executed successfully, Unix will make two identical copies of address spaces, one for the parent and the other for the child. Both processes will start their execution at the next statement following the fork() call.[Ref:http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html].

So,if I execute the following code:

#include <stdio.h> int main(void) { printf("Hello\n"); fork(); printf("World\n"); return 0; } 

I think it will print

Hello World World 

But when I run the program it prints

Hello World Hello World 

Please explain where am I lacking in concept?

5

1 Answer 1

2

This is about buffering. When you print "hello" it doesn't go to output immediately. Instead, it goes to a buffer. It's still there during the fork, so, when each task terminates and flushes its buffer, there are two copies to send to output.

To counter this, you could specify unbuffered I/O or call fflush before the fork to flush the buffer.

Sign up to request clarification or add additional context in comments.

3 Comments

@Gilles removed my mention of using terminal input to flush terminal output. I still think it's worth mentioning. fflush works as well, of course. It's just fancier.
I don't see what makes it “fancier”. fflush has the advantage of being simpler and of always working. Using terminal input only works if you're reading terminal input, which is often not the case.
@Gilles, my idea is that OP is a beginner, so not acquainted with a wide spectrum of system calls. I want to reply in simple terms so that he gets the idea without having to delve into new documentation. Terminal I/O is where most people start out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.