Search code examples
clinuxforksystem-calls

fork()'ing example


I am having some trouble understanding the following code. If I run the program with a single argument (argc of 2), the for fork() runs twice and 2 child processes are created. So total processes should be 3, right? But my Professor said they're supposed to be 4. I don't understand why.

If one of the child process creates another fork(), why not the second one? What happens when we the program with two arguments? Could someone explain step-wise?

#include <unistd.h>
int main(int argc, char *argv[])
{
    int c;
    for (c = 0; c < argc; c++) {
        (void) fork();
    }

    return 0;
}

Solution

  • Could someone explain step-wise?

    Step 1: Process 1 calls fork() when c = 0. Process 2 is created as copy of the current state.

    Step 2: Process 1 calls fork() when c = 1. Process 3 is created as copy of the current state.

    Step 3: Process 2 calls fork() when c = 1. Process 4 is created as copy of the current state.

    Step 4: Process 3 starts with c = 1, thus the for loop terminates after incrementing it to c = 2, no further processes created.

    Step 5: Process 4 starts with c = 1, thus the for loop terminates after incrementing it to c = 2, no further processes created.

    Total number of processes: 4.