How to count the fork processes position

2019-08-17 06:59发布

问题:

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);
}

回答1:

This is just not so easy. The main reason is that your forking schema generates a tree of processes. Numbering nodes in a tree is not obvious. Worst, forking introduces concurrency, then you cannot really control the order in which processes run.



回答2:

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:

       0
   1       2
 3   4   5   6
7 8 9 A B C D E

Child 0xA=10 knows it is the right child, has a depth of 3, its parent is 4:

own_position = (i_am_right_child ? 1 : 0) +                  // nth child under parent
               2 * (parent_id - (2**(own_depth - 1) - 1)) +  // 2 * offset of parent in its line
               2**own_depth - 1                              // first index of own line

10 = 1 + 2 * (4 - 2**(3 - 1) + 1) + 2**3 - 1

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.



标签: c linux fork