Child and Parent pid with fork();

匆匆过客 提交于 2019-12-12 04:54:08

问题


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?.


回答1:


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.



来源:https://stackoverflow.com/questions/26310824/child-and-parent-pid-with-fork

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!