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?

Hailey
  • 157
  • 1
  • 18
  • Strange,I am getting expected output. Hello World World – Rusty Aug 09 '16 at 06:12
  • I think if you use printf() you can't have 'Hello World World' o/p.correct me if I am wrong. – Hailey Aug 09 '16 at 06:19
  • You will have "Hello World World" as output,I simply copied and compiled the code,and got the same and this is what I expected. – Rusty Aug 09 '16 at 06:23
  • check these too. http://stackoverflow.com/questions/34978568/why-strange-behavior-of-fork-system-call http://stackoverflow.com/questions/8255388/fork-behavior-in-linux – Rusty Aug 09 '16 at 06:28
  • 1
    [Also posted on CS.SE](http://cs.stackexchange.com/q/62414/755). Please [do not post the same question on multiple sites](http://meta.stackexchange.com/q/64068). Each community should have an honest shot at answering without anybody's time being wasted. – D.W. Aug 09 '16 at 06:52

1 Answers1

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.

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Andrew
  • 41
  • 3
  • @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. – Andrew Aug 10 '16 at 22:10
  • 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 'SO- stop being evil' Aug 10 '16 at 22:21
  • @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. – Andrew Aug 12 '16 at 04:33