How can I add a counter in my code in order to be able to count the position of each process. Right now I'm getting the following output:
Process Pid: 6179 PPid: 4378 (position: ?).
Process Pid: 6181 PPid: 6179 (position: ?).
Process Pid: 6180 PPid: 6179 (position: ?).
Process Pid: 6185 PPid: 6180 (position: ?).
Process Pid: 6183 PPid: 6181 (position: ?).
Process Pid: 6182 PPid: 6181 (position: ?).
Process Pid: 6184 PPid: 6180 (position: ?).
All I want is to be able to output the Pid position in the tree:
Process Pid: 6179 PPid: 4378 (position: 1).
Process Pid: 6181 PPid: 6179 (position: 3).
Process Pid: 6180 PPid: 6179 (position: 2).
Process Pid: 6185 PPid: 6180 (position: 7).
Process Pid: 6183 PPid: 6181 (position: 5).
Process Pid: 6182 PPid: 6181 (position: 4).
Process Pid: 6184 PPid: 6180 (position: 6).
Thank you
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <math.h>
/*Childs to be created*/
#define NUM_CHILDS 2
/*Child launcher*/
void launchChild(int nivel,int n){
printf("Process Pid: %d PPid: %d (position: ?).\n",getpid(),getppid(),n);
if(nivel<NUM_CHILDS){
int process;
process = fork(); /*Child or parent?*/
if(process!=0){ /*We are parent*/
process=fork();
if(process==0){ /*We are child*/
launchChild(nivel+1,n);
}
}
else{ /*We are parent*/
launchChild(nivel+1,n);
}
}
wait(NULL);
}
int main(void){
launchChild(0,1);
}