我正在尝试编写一个函数,该函数使用 C 中的 fork 递归地计算来自给定 int n 的结果斐波那契数。
函数说明如下: 如果 print 为真,则打印它。否则,将其提供给父进程。该解决方案应该是递归的,并且它必须为每次调用派生一个新的 child 。每个进程都应该恰好调用 doFib() 一次。方法签名无法更改。无法使用辅助函数。
以下是我迄今为止根据对 fork 的理解所写的内容。我正在尝试 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 调用的值,以便我可以组合它们?
3.我的 fork 是否正确?一把 fork 我很有信心,两把让我头疼。
这是我目前正在为即将到来的考试做准备的一系列期中练习题。
最佳答案
1) 调用 waitpid
两次。
2) waitpid
调用会将其置于status
。
3) 两件事:首先,要终止 fork 进程,请使用_exit
,而不是exit
。 exit
函数可能会弄乱父进程仍在使用的文件描述符。这对你来说并不重要,但为什么要养成坏习惯呢?其次,您不需要 else if (pid2 > 0)
子句。就剩下这些了。</p>
关于c - 使用 Fork 的递归斐波那契数列(C 语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9156823/