递归斐波那契使用叉(C语言) [英] Recursive Fibonacci using Fork (in C)

查看:214
本文介绍了递归斐波那契使用叉(C语言)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个递归使用叉子在C定intñ计算所产生的Fibonacci数的函数。

I'm attempting to write a function that recursively computes the resulting fibonacci number from a given int n using forks in C.

下面是函数说明:如果打印是真实的,打印出来。否则,它提供给父进程。该解决方案应该是递归的,它必须产生一个新的孩子每个呼叫。每个过程应该调用doFib()一次。方法签名不能被改变。辅助函数,不能使用。

Here is the function specification: If print is true, print it. Otherwise, provide it to the parent process. The solution should be recursive and it must fork a new child for each call. Each process should call doFib() exactly once. The method signature cannot be changed. Helper functions cannot be used.

下面是我迄今根据我的叉子的理解写的。我试图叉两次,所以我可以生成两个子进程。一做FIB(N-1)和一做FIB(N-2)。这样我可以抓住这两个结果并结合他们。

Here is what I've written thus far based on my understanding of fork. I'm attempting to fork twice so I can spawn two child processes. One to do fib(n-1) and one to do fib(n-2). This way I can grab both of the results and combine them.

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));
    } 
}

我的问题:

My questions:

1。如何从两个子进程抢到两个出口值吗?我知道如何抢单(见code),但我要如何抓住他们两个?

1. How do I grab both of the exit values from the two child processes? I know how to grab one (see code), but how do I grab them both?

2。由于doFib不返回值,我怎么得到我的电话doFib的价值在任何我的子进程,所以我可以将它们组合起来?

2. Since doFib does not return a value, how do I get the value of my doFib call in either of my child processes so I can combine them?

3。我做我的分叉正确?我相信一个叉,二是让我头疼。

3. Am I doing my forking correctly? I was confident with one fork, two is making my head hurt.

这是一个系列的,我目前通过努力prepare为即将到来的考试练习中期问题。

推荐答案

1)呼叫 waitpid函数两次。

2) waitpid函数通话将其放在状态

3)两件事情:第一,终止一个分叉过程中,使用 _exit ,而不是退出。在退出父仍在使用功能,可以搞砸了文件描述符。它不会在你的情况关系,但是为什么学坏习惯?其次,你不需要否则如果(PID2大于0)条款。这是所有剩下的。

3) Two things: First, to terminate a forked process, use _exit, not exit. The exit function can mess up file descriptors that the parent is still using. It doesn't matter in your case, but why learn bad habits? Second, you don't need the else if (pid2 > 0) clause. That's all that's left.

这篇关于递归斐波那契使用叉(C语言)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆