[Solved] How many processes are created in this program? [duplicate]


Here’s how I would find the answer. After each fork(), I would print the current process ID. When I run the program, I would note all of the unique process IDs, and that would tell me how many processes existed:

This is my program:

#include <stdio.h>
#include <unistd.h>
int main() {

    /* fork a child process */
    pid_t pid = fork();
    printf("fork I: %d\n", getpid()); fflush(stdout);

    if (pid < 0) {
        fprintf(stderr, "Fork failed");
        exit(-1);
    } else if (pid != 0) {
        /* fork another child process */
        fork();
        printf("fork II: %d\n", getpid()); fflush(stdout);
    }

    /* fork another child process */
    fork();
    printf("fork III: %d\n", getpid()); fflush(stdout);
    return 0;
}

And here is my output:

fork I: 7785
fork I: 7786
fork II: 7785
fork III: 7785
fork III: 7786
fork II: 7787
fork III: 7788
fork III: 7789
fork III: 7787
fork III: 7790

In the running of my program, there seem to be 6 processes total, including the original process.

1

solved How many processes are created in this program? [duplicate]