charlesdk
charlesdk

Reputation: 176

Create process tree in particular order using fork()

I attempted to create a process tree in C like in the picture here:

enter image description 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

Answers (1)

lxop
lxop

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:

  • Each process prints its letter immediately when it starts
  • Each process (except A) then sends 'ok' to its parent
  • Each process (except A) then it waits for a 'go' message from its parent.
  • When it receives the 'go' message, it proceeds to create each of its children in order, waiting to receive 'ok' from each before creating the next.
  • When it has received 'ok' from its final child, it then sends 'ok' to its parent, unless it is A (has no parent), in which case it sends 'go' to each of its children in turn, waiting to receive 'ok' before moving on to the next child.
  • After creating its children, when a process receives 'go' from its parent, it sends 'go' to each of its children in turn, waiting to receive 'ok' back from each before moving on to the next.

This should be most of a solution, but not complete. You'll need some sort of finishing logic. I would suggest something like

  • When a process that has no children receives 'go' from its parent, it sends 'done' back to the parent.
  • When a process receives 'done' from all of its children, it sends 'done' to its parent.
  • When process A receives 'done from all of its children, the game is finished and everyone can pack up and go home.

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

Related Questions