An expert programmer decided to use multiple processes to do a simple job. (For the purposes of this problem, we'll ignore the sanity aspects of this design.)
The program executes, but the programmer gets more than he expects.
#include <iostream>
#include <unistd.h>
int main()
{
std::cout << "Hello ";
if (fork() == 0) {
std::cout << "World\n";
}
return (0);
}
Hint 1: The program outputs more than just "Hello World".
Hint 2:
A fork make an exact duplicate of the program.
Hint 3:
A fork make an exact duplicate of the program including
the program's memory.
Hint 4:
A fork make an exact duplicate of the program including
the program's memory which includes the I/O buffers.
Hint 5:
A fork make an exact duplicate of the program including
the program's memory which includes the I/O buffers and the data inside them.
Answer: The program first outputs "Hello" because of buffering, this goes into a buffer and is not output.
The fork is executed. A copy of the buffer is made.
The parent finishes. The parent's buffer is flushed. "Hello" is output.
The child's buffer has "Hello" already in it. The child adds "World" to this and flushed the buffer. "Hello World" is printed by the child.
Thus on the screen we see:
Hello Hello World
Note: The output is dependent on whether the child or the parent executes first. (We assumed parent.)