Dovahkiin
Dovahkiin

Reputation: 1239

fork a child process inside while loop

I'm fairly new to unix sys calls, and recently I ran into a problem where there are multiple fork() calls to a child process. And I am confused about the output.

int main() {
    int count = 0;
    int pid;
    if (!(pid = fork())) {

        while ((count < 2) && (pid = fork())) {
            count++;
            printf("Count for pid: %d: %d\n", getpid(), count);
        }
        if (count > 0) {
            printf("Count for pid: %d: %d\n", getpid(), count);
        }
    }
    if (pid) {
        printf("pid is %d, and we waitpid\n", pid);
        waitpid(pid, 0, 0);
        count = count << 1;
        printf("Count for pid: %d: %d\n", getpid(), count);
    }
}

and the output I got is:

pid is 12933, and we waitpid
Count for pid: 12933: 1
Count for pid: 12933: 2
Count for pid: 12933: 2
pid is 12935, and we waitpid
Count for pid: 12935: 1
Count for pid: 12933: 4
Count for pid: 12932: 0

So my question is, how come there are only 3 unique pid, shouldn't the fork in the while loop create way more child processes than 3?

Upvotes: 0

Views: 623

Answers (1)

HamidReza
HamidReza

Reputation: 727

You likely know about fork return value:

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

So, your code will traverses such a tree:

enter image description here

I have written the sequence number for each 'printf' function.

Upvotes: 2

Related Questions