I have a algorithm to create a N-processes using fork(). Processes are generating successfully because I drew them by hand.
The problem is when I try to print them (not needed as a tree) I find duplicated processes in output. Cant find why.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
void GenerateTree(int n){
printf("PID: %d | PPID: %d\n",getpid(),getppid());
int *ptr = mmap(NULL,n*sizeof(int),PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS,0,0);
int *ptr1 = mmap(NULL,sizeof(int),PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS,0,0);
ptr1[0]=0;
int z = 0;
while(z<n){
if(ptr1[0]<n-1){
pid_t pid;
pid = fork();
if(pid==0){
printf("PID: %d | PPID: %d\n",getpid(),getppid());
ptr[ptr1[0]] = getpid();
z++;
ptr1[0]=ptr1[0]+1;
if(ptr1[0]<n-1){
fork();
printf("PID: %d | PPID: %d\n",getpid(),getppid());
ptr[ptr1[0]] = getpid();
ptr1[0]=ptr1[0]+1;
z++;
}
else{
break;
}
}
else{
wait(NULL);
break;
}
}
else{
break;
}
}
}
int main(int argc, char const *argv[])
{
GenerateTree(11);
return 0;
}
And the output looks like this.
PID: 5480 | PPID: 1168
PID: 5481 | PPID: 5480
PID: 5481 | PPID: 5480
PID: 5482 | PPID: 5481
PID: 5483 | PPID: 5481
PID: 5484 | PPID: 5482
PID: 5483 | PPID: 5481
PID: 5484 | PPID: 5482
PID: 5486 | PPID: 5484
PID: 5485 | PPID: 5483
PID: 5487 | PPID: 5483
PID: 5488 | PPID: 5484
PID: 5489 | PPID: 5485
PID: 5490 | PPID: 5486
Thanks for your help!