Bill said:
1) The root of the question is off-topic, but I'll answer.
You need to flush the output stream before the fork. The
first printf is putting "Hello\n" into the buffer. The child
inherits that buffer before it is flushed, so when it prints
"World", it is also printing the "Hello" that the parent had
put in the buffer.
It is worth noting that there will be a difference in the behaviour of
the OPs posted code, depending on whether or not he redirects stdout to
a file.
<note>
The following will be semi-off-topic. While it primarily deals with
behaviours invoked from non-C-standard functions (fork()), it also
deals with the side-effects of behaviours specified by the C standard.
As I cannot find a corresponding thread in any Linux or Unix newsgroup,
I thought it worthwile to respond here. My apologies to newsgroup
topicality pedants.
</note>
In the case of a redirect, stdout is buffered, and not automatically
flushed with the '\n' character (C standard behaviour). This means
that, in the case of the OPs code,
a) the parent process will not flush it's output until the termination
of the main() function, which implies that the buffer is not yet
flushed when fork() is invoked, and
b) the child process will not flush it's output until the termination
of the main() function.
So, in the case of a redirect to file, the output will consist of
a) a line reading "Hello", generated by the parent process and written
on termination of the parent process,
b) a line reading "Hello", inherited from the parent process by the
child process, and written on termination of the child process, and
c) a line reading "World", generated by the child process and written
on termination of the child process
OTOH, in the case of no redirect, stdout is buffered, and flushed
automatically with each '\n' (again, by the C standard). Thus, the
child process will /not/ inherit an unflushed buffer, and will not
print the redundant "Hello". For this pattern, the output will consist
of
a) a line reading "Hello", generated by the parent process and written
on termination of the parent process, and
b) a line reading "World", generated by the child process and written
on termination of the child process