drdot
drdot

Reputation: 3347

Two simple case studies of fork()

I wrote two simple programs to understand the fork() API.

The first program:

int multiple_fork(){
    fork();     //prints 2 times
    fork();     //prints 4 times
    printf("hello\n");
    exit(0);
}

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

This program will print "hello" four times because the first fork() produces a child thread (C0), the second fork produces another two child threads C1 and C2 from parent thread (P) and C0, respectively. So far so good.

The second program:

#define N 2
int main(){
    int status, i;
    pid_t pid;
    /* parent creates N children */
    for(i = 0; i < N; i++) 
        if((pid = fork()) == 0){ /* Child */
            printf("Child\n");
            exit(100+i);
        }
    return 0;
}

This will print "Child" twice which I do not understand because I expect the "Child" get printed three times. Reason: in the first loop, one child process (C0) is generated so this child will print "Child" once. Since C0 contains the same address space as parent process P. Then both P and C0 will execute the second loop. So C1 and C2 are generated from P and C0, respectively. So for C1 and C2, each child process will print "Child" once. Therefore, it should print "Child" three times. But apparently, I am wrong. Could someone explain what has happened?

Upvotes: 0

Views: 125

Answers (1)

chrk
chrk

Reputation: 4215

When fork(2) returns, only the child will have pid == 0, so only the two children, forked on each iteration, will enter the if block and print.

These two children won't continue forking, because you call the exit(2) system call.

Upvotes: 2

Related Questions