0

I am trying to write a program which will create processes as follows :

P1 -> P2 -> P3
P1-> P4 ->P5

P2, P3 need to be finished before P4, P5

my code so far :

#include<stdio.h>
  
  
int main()
{
    for(int i=0;i<2;i++) // loop will run 2 times
    {
        if(fork() == 0)
        {
            printf("[son] pid %d from [parent] pid %d\n",getpid(),getppid());
            exit(0);
        }
    }
    for(int i=0;i<2;i++) // loop will run 2 times
    wait(NULL);
      
}

I am facing difficulties in running P4 and P5 after P2,P3 if they are forked from P1. Kindly help

2014GAM
  • 103
  • 1
  • 9

1 Answers1

0

If you want P2 and P3 to be finished before P4 and P5 starts, P1 should wait for them to finish after the first fork, not after the entire loop that did 2 forks.

You are starting P2 and P4 in parallel.

That's the first problem, apart from that not sure how P3 and P5 are created, since child processes (P2 and P4) are immediately exiting without creating them. You probably need to call some forks from the inside of the IF, no?

Piotr
  • 504
  • 4
  • 6