C程序的15个进程的二叉树

时间:2015-09-07 22:14:48

标签: fork

我们如何制作一个在C程序中提供15个进程的fork二叉树?我试着编写代码但是我对15个进程有些困难。另外,叉总是困惑我! 此外,对于每个进程,我们应该打印出其进程ID和其父进程的id。

这是我的代码:

((当我复制粘贴我的代码时,我无法发布问题))

如果你可以帮助我使用正确的代码,我会非常高兴

谢谢

1 个答案:

答案 0 :(得分:0)

你需要继续分叉。这将使用fork为您生成15个进程:

#include <stdlib.h>
#include <stdio.h>

int main() {
    int returnPid;
    int numForks = 0;
    while (numForks++ < 15) {
        if ((returnPid = fork()) == -1) {
            perror("can't fork");
            exit(1);
        } else if (returnPid == 0) {
            // Child process
            printf("Child: returnedPid = % d, my pid = %d, parent pid = %d, fork count = %d \n", returnPid, getpid(), getppid(), numForks);
        } else {
            printf("Parent: returnedPid = %d, my pid = %d, parent pid = %d \n ", returnPid, getpid(), getppid(0));
            exit(0);
        }
    }
    exit(0);
}

输出:

Parent: returnedPid = 15622, my pid = 15621, parent pid = 13927
 Child: returnedPid =  0, my pid = 15622, parent pid = 1, fork count = 1
Parent: returnedPid = 15623, my pid = 15622, parent pid = 1
 Child: returnedPid =  0, my pid = 15623, parent pid = 1, fork count = 2
Parent: returnedPid = 15625, my pid = 15623, parent pid = 1
 Child: returnedPid =  0, my pid = 15625, parent pid = 15623, fork count = 3
Parent: returnedPid = 15626, my pid = 15625, parent pid = 1
 Child: returnedPid =  0, my pid = 15626, parent pid = 1, fork count = 4
Parent: returnedPid = 15627, my pid = 15626, parent pid = 1
 Child: returnedPid =  0, my pid = 15627, parent pid = 15626, fork count = 5
Parent: returnedPid = 15628, my pid = 15627, parent pid = 1
 Child: returnedPid =  0, my pid = 15628, parent pid = 1, fork count = 6
Parent: returnedPid = 15629, my pid = 15628, parent pid = 1
 Child: returnedPid =  0, my pid = 15629, parent pid = 15628, fork count = 7
Parent: returnedPid = 15631, my pid = 15629, parent pid = 1
 Child: returnedPid =  0, my pid = 15631, parent pid = 15629, fork count = 8
Parent: returnedPid = 15632, my pid = 15631, parent pid = 1
 Child: returnedPid =  0, my pid = 15632, parent pid = 1, fork count = 9
Parent: returnedPid = 15634, my pid = 15632, parent pid = 1
 Child: returnedPid =  0, my pid = 15634, parent pid = 15632, fork count = 10
Parent: returnedPid = 15635, my pid = 15634, parent pid = 1
 Child: returnedPid =  0, my pid = 15635, parent pid = 15634, fork count = 11
Parent: returnedPid = 15636, my pid = 15635, parent pid = 1
 Child: returnedPid =  0, my pid = 15636, parent pid = 15635, fork count = 12
Parent: returnedPid = 15637, my pid = 15636, parent pid = 1
 Child: returnedPid =  0, my pid = 15637, parent pid = 15636, fork count = 13
Parent: returnedPid = 15638, my pid = 15637, parent pid = 1
 Child: returnedPid =  0, my pid = 15638, parent pid = 15637, fork count = 14
Parent: returnedPid = 15639, my pid = 15638, parent pid = 1
 Child: returnedPid =  0, my pid = 15639, parent pid = 15638, fork count = 15