Recursive Fibonacci using Fork (in C)

2020-07-13 08:19发布

问题:

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

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.

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. 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:

1) Call waitpid twice.

2) The waitpid call will put it in status.

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.