Home > Blockchain >  Is program count everything right with fork and processes?
Is program count everything right with fork and processes?

Time:12-08

I just need to know if i'm right. With this forks() before the switch in the loop that will gonna be made one time, the number of processes should be 5 right? And if i'm gonna add more forks() this number gonna increase to 9,17,etc.? And i'm courius in this case how this processes are creating new ones, is the next forks() only creating new processes from childs or from parent too because i can't draw it properly because i dont know how to check processes creating new ones. Maybe it is obvious question but i think i miss something and i want to make sure that i understand it good.

Thanks!

Is it gonna look like this? (i made a draw)

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include  <sys/types.h>

void processTree()
{
    pid_t pid_t = getpid();
    int tmp = pid_t;
    printf("PID : %d\n",pid_t);
    char buffer [128];

    for(int i = 0; i < 1; i  )
    {
        int pid_child;
        fork();
        fork(); //if i am gonna add more fork there will be 9,17,etc processes?
        switch(pid_child = fork())
        {
        case -1:
            exit(-1);
        case 0:
            pid_t = pid_child;
            
            
            printf("UID: %d, GID: %d, PID: %d, PPID: %d\n", getuid(), getgid(), getpid(), getppid()); fflush(stdout);
            break;
        
        }
    

 }

int main()
{
    processTree();
    return 0;
}

CodePudding user response:

The for loop iterates once, so it's irrelevant. The show starts with one process, the one that's executing main(), which does a

fork();

There are now two processes. Each one of the two processes does a

fork();

There are now four processes. Each one of those four processes does a

switch(pid_child = fork())

There are now eight processes.

Nothing else that the shown program did before, or did after all the fork() is material, with respect to the total number of processes in the end.

Grand total: eight processes.

  • Related