I have this question on fork() function in C, I just couldn’t figure how it works

  Kiến thức lập trình

in this code snippet:

#include <stdio.h> 
int main(int argc, char **argv){
    for(int i=0;i<2;i++){
    printf("i: %dn",i);
    if(fork() | fork()){
        fork();
    }
    }
}

the question is how many times the number 1 is printed to stdout, its 7, but i couldn’t figure how and why ,like how does the function fork() work such that the “father” process creates 6 other processes?

I thought that the first fork created one other process(making 2 in total), and the second fork creates two other (making 4 in total), and then lastly the nested fork would create 4 other processes (making 8 in total), but that doesn’t seem the case, and i think I’m messing something here.

New contributor

Thatoneguy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT