Michael
Michael

Reputation: 29

Fork processes in C

I have some C code using fork but I don't understand how it works

int hijo,i,N;
int main(int argc, char*argv[]){
    N=atoi(argv[1]);
    for(i=0;i<N;i++)
      if((hijo=fork())>0)break;
}

Why does this program create only one child process of the previously created process and doesn't create a process for each of the processes that exist before do the fork?

Upvotes: 1

Views: 135

Answers (1)

hyde
hyde

Reputation: 62777

The code is equal to this:

int hijo;

int main(int argc, char*argv[]){

    if (argc < 2) return 1; // let's not crash

    // assume i and N are global variables not shown...
    N=atoi(argv[1]);
    i = 0;
    if (N < 1) return 0; // do not enter loop if N < 1

    do {
        hijo=fork();
    } while (hijo <= 0 && ++i < N);
}

From this we can more easily see, that for the original parent process, where hijo value is the pid of the first child, the loop condition is false immediately, and loop ends.

Same repeats for every child process, so a process can only be parent (hijo > 0) for one forked process.

Upvotes: 1

Related Questions