samedi 26 avril 2014

Understand Fork


Vote count:

0




I found this code from U of Regina's CS website. http://ift.tt/1fhDxZW



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

int main()
{
cout << "0. I am process " << getpid() << endl;
(void) fork();
cout << "1. I am process " << getpid() << endl;
(void) fork();
cout << "2. I am process " << getpid() << endl;
}


The output of the program is as follows:



$ ./a.exe
0. I am process 2196
1. I am process 2196
1. I am process 6560
2. I am process 6560
2. I am process 4472
2. I am process 2196
2. I am process 2288


I would like to make sure that I understood this program correctly. Does the creation diagram look something like this:



2196
/ \
2196 6560
\ / \
2288 6560 4472


The first process created is 2196(parent) and that created 6560(child). Since fork is called again 6560(now parent) 4472 is created. Meanwhile, 2196(from the first fork) still running and created 2288(child). So in total, 4 processes were made (2 parents and 2 children). Is this correct?



asked 25 secs ago






Aucun commentaire:

Enregistrer un commentaire