I am trying to write a function that recursively computes the resulting fibonacci number from a given int n using forks in C.
Here is the specification of the function: If the print is correct, print it. Otherwise, provide the parent process. The solution must be recursive, and it must develop a new child for each challenge. Each process must call doFib () exactly once. The signature of the method cannot be changed. You cannot use helper functions.
Here is what I have written so far based on my understanding of the plug. I am trying to split twice, so I can create two child processes. One to make fib (n-1) and one to make fib (n-2). That way I can capture both 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 to get both values ββfrom two child processes? I know how to capture one (see Code), but how can I capture them?
2. Since doFib does not return a value, how do I get the value of my doFib call in any of my child processes so that I can combine them?
3. Am I doing my job right? I was sure of one plug, two had a headache.
This is an interim issue in the practice of the series that I am currently working on to prepare for the upcoming exam.
source share