首页 文章

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

提问于
浏览
6

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

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

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

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. 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. 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. Am I doing my forking correctly? I was confident with one fork, two is making my head hurt.

This is a practice midterm problem of a series that I'm currently working through to prepare for an upcoming exam.

1 回答

  • 5

    1)两次调用 waitpid .

    2) waitpid 调用将它放在 status 中 .

    3)两件事:首先,要终止分叉进程,请使用 _exit ,而不是 exit . exit 函数可能会弄乱父级仍在使用的文件描述符 . 它不需要 else if (pid2 > 0) 条款 . 那个's all that'离开了 .

相关问题