使用Fork的递归Fibonacci(在C中)

我正在尝试编写一个函数,该函数使用C中的forks从给定的int n递归计算得到的fibonacci数。

这是function规范:如果print为true,则打印它。 否则,将其提供给父进程。 解决方案应该是递归的,它必须为每个调用分叉一个新的子节点。 每个进程应该只调用一次doFib()。 方法签名无法更改。 无法使用辅助函数。

这是我到目前为止根据我对fork的理解所写的内容。 我试图分叉两次,所以我可以产生两个子进程。 一个做fib(n-1),一个做fib(n-2)。 这样我就可以抓住两个结果并将它们组合起来。

static void doFib(int n, int doPrint) { pid_t pid1; pid_t retpid1; int status1; pid_t pid2; pid_t retpid2; int status2; pid = fork(); if (pid == 0) // Child Process 1 { exit(100); // sends 100 to the parent } else if (pid > 0) // Parent Process 1 { pid2 = fork(); if (pid2 == 0) // Child Process 2 { exit(200); // sends 200 to the parent } else if (pid2 > 0) // Parent Process 1 { } retpid = waitpid(pid,&status,0); if (pid != retpid) { printf("waitpid error\n"); } printf("I got this value from my child process 1: %d\n", WEXITSTATUS(status)); } } 

我的问题:

1.如何从两个子进程中获取两个退出值? 我知道如何抓住一个(见代码),但我如何抓住它们?

2.由于doFib不返回值,如何在我的子进程中获取doFib调用的值,以便将它们组合起来?

我正在做正确的分叉吗? 我对一个叉子很有信心,两个让我头疼。

这是我正在努力为即将到来的考试做准备的一系列练习中期问题。

1)两次调用waitpid

2) waitpid调用将使其处于status

3)两件事:首先,要终止分叉进程,请使用_exit ,而不是exitexit函数可能会弄乱父级仍在使用的文件描述符。 在你的情况下没关系,但为什么学习坏习惯? 其次,你不需要else if (pid2 > 0)子句。 这就是剩下的一切。