Reputation: 74
I have to make a binary proccessing tree to sort some records but i've got stuck at the creation. I am using this recursive code to product a binary tree of proccesses:
void proc_tree(int i, int current_depth, int max_depth, int rec, int offset)
{
pid_t kid = fork();
if(kid == 0)
{
printf("[%d,%d]: start: %d, end: %d\n", i, current_depth, rec, offset);
if(current_depth < max_depth)
{
int nodes= pow(2, current_depth);
if(i >= nodes)
i = 0;
proc_tree(2*i+1, current_depth+1, max_depth, rec, offset/2);
proc_tree(2*i+1, current_depth+1, max_depth, offset/2, offset);
}
}
}
I have not included any error checking i am doing and i haven't included the code of the father since the only thing he is doing atm is to wait for the children to end.
The output i am getting is this:
[0,0]: start: 0, end: 180
[1,1]: start: 0, end: 90
[3,2]: start: 0, end: 45
[4,2]: start: 46, end: 90
[2,1]: start: 91, end: 180
[1,2]: start: 91, end: 90
[2,2]: start: 91, end: 180
As you can see most of the values are fine but at depth = 2 the first node ([1,2]) and ([2,2]) have wrong values. Since we got a total of 181 records at depth = 2 there are 4 nodes so each node should be managing about 45 records each. So [1,2] should be 91, 136 and [2,2] should be 137, 180.
I am calling the function from main like this
proc_tree(0, 0, 2, 0, 180);
Any help would be appreciated. Thanks in advance.
Upvotes: 0
Views: 66
Reputation: 60017
You do realise that fork
creates a new process and each process has its own copy of the memory.
Also the OS is free to process in any order as it sees fit.
I guess you are thinking of recursion. In which case you do not need fork.
Upvotes: 2