0

Possible Duplicate:
working of fork in c language

I have a very simple program that i am trying to understand fork() Now, in my program is fork() copying the whole program everytime it encounters fork() or the line above(as the parent)?

I am getting weird results which is making it harder to understand.

#include <iostream>
#include <unistd.h>
using namespace std;

int main()                  
{                       
cout << "Ha! " << endl;         
fork();                     
cout << "Ho! " << endl;         
fork();                 
cout << "He! " << endl;         

}       

output:

apple.seed@wint:~$ ./program1
Ha! 
Ho! 
He! 
Ho! 
He! 
apple.seed@wint:~$ He! 
He! 

At the fork() point, the operating system will create a new process that is exactly the same as the parent process(whatever that may be?). This means all the state that was talked about previously is copied, including open files, register state and all memory allocations, which includes the program code.(so when the program reaches fork() the whole program is copied?)

Community
  • 1
  • 1
  • This question has more or less been asked before. Here's an answer that seems to be fairly thorough: http://stackoverflow.com/a/6211268/534109 – Tieson T. Oct 07 '12 at 23:28
  • 2
    I don't really see a question in your post, but if there is one, I think the answer is yes? – Kerrek SB Oct 07 '12 at 23:34
  • 1
    What seems odd about the output? Explaining that will help us understand what your question is. – Vaughn Cato Oct 07 '12 at 23:38
  • I think my question is very clear: "Now, in my program is fork() copying the whole program everytime it encounters fork() or the line above(as the parent)?" –  Oct 08 '12 at 01:22

1 Answers1

6
              He!     <-- original
             /
        Ho! <
       /     \
      /       He!     <-- forked from original's second fork call
     /
Ha! <          
     \
      \       He!     <-- forked from origin's first fork call
       \     /
        He! <
             \    
              He!     <-- forked from the first fork 

              ^
              |
              +----------- after second forks

< = fork calls.

Amber
  • 507,862
  • 82
  • 626
  • 550