Reputation: 176
I attempted to create a process tree in C like in the picture here:
Please note that the process tree must be created so that it follows the alphabetical order.
My code:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main(int argc, char **argv)
{
pid_t b,c,d,e,f,g,h;
if(b = fork() == 0)
{
if(e = fork() == 0){}
else
{
if(f = fork() == 0)
{
sleep(1);
if(h = fork() == 0){}
}
}
}
else
{
if(c = fork() == 0)
{
sleep(0.5);
if(g = fork() == 0){}
}
else
{
if(d = fork() == 0){}
}
}
return 0;
}
I used sleep to delay the processes so they can be created in the right order. But I think this isn't the correct way to do it, can anyone please show me the correct and more reliable way?
Upvotes: 2
Views: 1424
Reputation: 8625
You're correct that using sleeps is not the right way to do this. You will need to use some form of interprocess communication (IPC).
I would suggest that the simplest way is to use a pipe between parent-child. It will need to be multi-level to support the relationship between B, C, and E.
Something like:
This should be most of a solution, but not complete. You'll need some sort of finishing logic. I would suggest something like
You will need a better structure than a nested bunch of if/else blocks. I suggest making some sort of simple table in a static variable at the top of the file to map which children each node has, and setting a variable to the name of the process before forking it.
Functions will very much be your friend in this exercise.
Upvotes: 1