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);
}
The forked process has all the information of its parent up to its spawning. This means that the forked process knows the "position" of the parent. Further you, the programmer, know the spawn mechanism. Say, you always fork two children, up to a depth of 3:
Child 0xA=10 knows it is the right child, has a depth of 3, its parent is 4:
If you fork more than two children, then try change the 2 in the formula, too.
Different numbering systems are possible. This here is called breadth-first search.
This is just not so easy. The main reason is that your
fork
ing schema generates a tree of processes. Numbering nodes in a tree is not obvious. Worst,fork
ing introduces concurrency, then you cannot really control the order in which processes run.