-4

I have this bit of code :

#include<stdio.h>
void createChild(){
 int pid;
pid=fork();
if(pid<0){
 printf("creation error");exit()
}
if(pid>0)return;
printf("Processus of number %d\n",getpid());
}

int main()
{
  createChild();
  createChild();
  createChild();
} 

I need to know how many process this code generate and a proper explanation ? please any help

Sora
  • 2,465
  • 18
  • 73
  • 146

1 Answers1

1

Here is what happens:

Process: Actions

1: [fork (creates 2)] [fork (creates 3)] [fork (creates 5)] [end of main]
2:                    [fork (creates 4)] [fork (creates 6)] [end of main]
3:                                       [fork (creates 7)] [end of main]
4:                                       [fork (creates 8)] [end of main]
5:                                                          [end of main]
6:                                                          [end of main]
7:                                                          [end of main]
8:                                                          [end of main]

You can see a clear exponential of base two here. Each fork() creates a child that starts execution from the return of the fork call. (you can differ the child from the parent with the return value.)

Guilherme Bernal
  • 8,183
  • 25
  • 43