The following code outputs a series of processes, exactly what it does is:
_PARENT_
/ \
/ \
child_2 child_3
/ \ / \
/ \ / \
/ \ / \
g_child_4 g_child_5 g_child_6 g_child_7
This is the output:
Process Pid: 929 PPid: 928 (position: 2).
Process Pid: 930 PPid: 928 (position: 3).
Process Pid: 931 PPid: 929 (position: 4).
Process Pid: 932 PPid: 929 (position: 5).
Process Pid: 934 PPid: 930 (position: 7).
Process Pid: 933 PPid: 930 (position: 6).
My question is, how can I get the grandchild_4 and 5 pass to child_2 their position values and child_2 sum it and pas it to parent? And same thing with grandchilds_6 and 7 passing their position values to child_3 and sum it to pass it to parent?
All I'm trying to get is to be able to print the sum of the position values of all grandchilds so at the output I can have:
Process Pid: 929 PPid: 928 (position: 2).
Process Pid: 930 PPid: 928 (position: 3).
Process Pid: 931 PPid: 929 (position: 4).
Process Pid: 932 PPid: 929 (position: 5).
Process Pid: 934 PPid: 930 (position: 7).
Process Pid: 933 PPid: 930 (position: 6).
Result 22.
Note: no pipes, FIFOs or maps can be used.
This is my code:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <math.h>
/*
* NUMBER OF LEVELS TO BE CREATED
*/
#define NUM_LEVEL 2
/*
* Child launcher
*/
int launchChild(int nivel,int n){
//sleep(1);
if(nivel>0) printf("Process Pid: %d PPid: %d (position: %d).\n",getpid(),getppid(), n+1);
if(nivel<NUM_LEVEL){
pid_t process = fork();//Child or parent?
if(process!=0){// Parent
process=fork();//Child or parent?
if(process==0){//Child
launchChild(nivel+1,2*n+2);
wait(NULL);
}
}
else{//Child
launchChild(nivel+1,2*n+1);
}
wait(NULL);
}
}
/*
* Main function
*/
int main(void){
launchChild(0,0);
}