Skip to main content
gamedev.net
🔒 Locked

fork()

Started by Zekk 3 replies 900+ views
Original Post
Zekk
Zekk
Hi I am trying to make a binary tree of processes w/ fork() in c/c++.

i.e. 1 parent 2 child 2 childs(now parents) have 4 childern(now parents)... 8 childern etc.

I got the first layer down but I am having trouble figuring out what to do next. Any help would be appreciated.

void Child(int, int, int);void Parent(int, int&);int main(){	int child = 0;	int i;	int r = 1;	i = 1;	int num = 0;	int parentid;	int child01 = 0;	int child02 = 0;	int pid;	 for(i=1; i < 2; i++)		  {		  cout << "Level\t Procs\t Parent\t Child1\t Child2\n";		  cout << "No.\t ID\t ID\t ID\t ID\n" << endl;		  }	// start main loop	 	 for(child = 0; child < 2; child++) {	 pid = fork ();	 	 //Parent Scope	   if (pid > 0)	   {		Parent(num, parentid);	   }	   //Child Scope	   else if (pid == 0)	   {		Child(r, child01, child02);	   }	   else if (pid < 0)	   {	     perror ("Can not create fork.");	     exit (1);	   }	 }	 cout << num << "\t" << getppid();	 cout << "\t" << parentid;	 }void Child(int r, int child01, int child02){	sleep(1);	child02 = getpid();	cout << "\t" << child02;		exit(1);}void Parent(int num, int& parentid){        parentid= getpid();}


[Edited by - Zekk on September 29, 2010 2:31:14 AM]
..
Gage64
Gage64
The first if statement should check if pid > 0, not pid != 0.

If you want a binary tree, then each child will need to create two children of its own. You'll also need a way to specify a maximum height for the tree, and when this height is reached, stop creating children.

BTW, is this a homework question?
Zekk
Zekk
I understand the maximum height part but not on how I can make the two children spawn more children.

i meant pid > 0
..
nolongerhere
nolongerhere
I think I have a textbook with that exact source in it... what book is it? Maybe I can assist you further.
Zekk
Zekk
I saw an example online and modified it. I think I need some loops to have the childern create more childern I am just a little lost after the first layer.

[Edited by - Zekk on September 29, 2010 12:16:28 PM]
..
samoth
samoth
Quote:
Original post by Zekk
I understand the maximum height part but not on how I can make the two children spawn more children.
In the exact same way as the first time, simply fork again twice. Why not just fork 8 times from the main instance, though... if you want 8 instances?

I don't understand how having a binary tree of processes makes any more sense than or has any advantage over just spawning a number of processes.

Something like...

int n = 0;

for(;;)
{
if(fork() > 0)
{
if(++n <= NUMBER_OF_PROCESSES_I_WANT)
exit();
}
else
break;
}
// now do whatever your processes are supposed to do

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.