Binary Tree of forked processes error

I cannot find the error in my program.

The program builds a binary tree of forked processes. The build function itself works while recursing. Where I believe I'm getting my error is some where within the pointers passing.

When it comes time to display the nodes (level ordered queue implementation) the root node is the only one displayed. It isn't until midway thru the build function that root no longer has a left. Before hand when the left or right is declared it is fine.

with 2 levels as command line input the result is:
Process: 1 Process ID: 10905 Process PPID: 1762
doh, forgot the code :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>
#include <queue>
using namespace std;

//struct for the nodes of the tree
struct nodeType
{
	pid_t      pid;
	pid_t      ppid;
	nodeType   *left;
	nodeType   *right;
};

//global root, was set globablly for testing
nodeType root;

void Build(nodeType *var, int depth)
{
	if (depth > 0)
	{
		int stat;
		if (fork() > 0)			
		{
			wait(&stat);
			if (fork() > 0)
				wait(&stat);
			else
			{
				nodeType left;
				left.pid = getpid();
				left.ppid = getppid();
				left.left = NULL;
				left.right = NULL;
				var->left = &left;
				Build(var->left, depth - 1);
			}
		}
		else
		{  
			nodeType right;
			right.pid = getpid();
			right.ppid = getppid();
			right.left = NULL;
			right.right = NULL;
			var->right = &right;
			Build(var->right, depth - 1);				
		}         		    
	}
}

void Display(nodeType *var)
{	
	int process = 0;
	queue<nodeType*> theQueue;
	theQueue.push(var);

	while(!theQueue.empty())
	{
		nodeType *temp = theQueue.front();
		theQueue.pop();
		cout<<"Process: "<<++process<<" Process ID: "<<temp->pid<<" Process PPID: "
			<<temp->ppid<<endl;		
			
		if(temp->left != NULL)		
			theQueue.push(temp->left);
		if(temp->right != NULL)
			theQueue.push(temp->right);
	}
}

int main(int argc, char *argv[])
{    
	cout<<getpid()<<endl;
	//check for correct command line input
	if (argc != 2)
	{
		cerr<<"Incorrect Input"<<endl;
		return 0;
	}

	int inputDepth = atoi(argv[1]);  
		
	//initialize the root variable
	root.pid = getpid();
	root.ppid = getppid();
	root.left = NULL;
	root.right = NULL;

	//recursively build tree
	Build(&root, inputDepth-1);
	
	//only display once, by the original process
	if (getpid() == root.pid)
	{		
		Display(&root);
	}
	cin>>inputDepth;
	return 0;
}

Topic archived. No new replies allowed.