LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Using fork() to create a binary tree (https://www.linuxquestions.org/questions/linux-newbie-8/using-fork-to-create-a-binary-tree-834638/)

mashhype 09-26-2010 06:34 PM

Using fork() to create a binary tree
 
Hi everyone,

Im new to this forum and new to programming. I am working on a project where I need to use the C language to generate a tree of processes. I understand how fork() works but I cant seem to get fork() to create two children from one parent and then have the two children create two more children.

Right now what i am seeing is a chain...where the parent creates one child...and that child creates another ONE child..etc.

Any suggestions...

Here is what I have so far:

for (i=0; i<n;i++){
if (childpid = fork()) break;

}
if (childpid == -1){
perror ("\n The fork failed\n");
exit(1);
}
printf("\n %d: process ID:%6ld parent ID:%6ld child ID:%6ld \n\n",i, (long)getpid(), (long)getppid(), (long)childpid);

linux_hy 09-26-2010 11:39 PM

try to the following code maybe help for you
but you need to modify this code for your requirement
and this code need to debug,it just a sample thinking of create process with recursion
layer is the count of child process
Code:

void process_tree(int layer)
{
  if(layer<=0) return;
  switch(fork()){
    case 0:
        process_tree(layer-1);
        break;
    case -1:
        fprintf(stderr,"fork failed\n");
        break;
    default:
        break;
  }
}


johnsfine 09-27-2010 06:17 AM

I think you want nested loops:

Outer loop iterates through the desired depth of the tree.
..Inner loop iterates through the desired number of children per parent.
....fork
....break out of inner loop if this process is the child
..break out of outer loop if the inner loop completed and this process is still the parent.

Notice also, that you will want an array of child pids since you want more than one child per parent.

mashhype 09-28-2010 01:27 AM

Hi again,

I got it to run. I used a switch statement nested inside a while loop. It works great! Thanks for the tips.


All times are GMT -5. The time now is 11:40 AM.