简体   繁体   中英

Child and Parent pid with fork();

I'm trying to make a program which make 9 child process, so I use fork 9 times only if we are the father, like this:

for (int i = 0; i < 9; i++) {   // Creo 9 hijos.
    if (child_pid > 0) {
        child_pid = fork();
        childs[i] = child_pid;
    }
    if (child_pid < 0)
        printf("Error...\n");
}

Now, I have to print on each children what children he is, starting from 0, so I was thinking about this:

printf("This is child #%d\n", getpid() - getppid());

But I'm not sure, Does this always work?, What if while the parent is creating childrens the operating system creates another process?, the number of children will be discontinued?. And finally, if the answer is yes, how can I make that the #n children knows that he is the children number n?.

You can use the i variable to tell which child you are in, but the logic of your loop is incorrect. It should go like this:

for (int i = 0; i < 9; ++i) {
    child_pid = fork();

    if (child_pid == 0) {
        // We are the child. The value of the i variable will tell us which one.
        // If i == 0 we are the first child, i == 1 and we are the second, and so on.
        printf("We are child #%d\n", i);
        exit(EXIT_SUCCESS);
    }

    if (child_pid < 0) {
        // Forking failed.
        perror("fork()");
        exit(EXIT_FAILURE);
    }

    // Otherwise we are the parent and forking was successful; continue the loop.
}

The operating system is not required to assign process IDs in sequential order. If another process is using the next one, it would be skipped over in a sequential assignment method, but the OS could really assign a random number as the pid as long as it is not in use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM