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); |
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) |
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. |
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. |