Hey all, I'm working on an assignment for my Operating Systems class and I've run into a snag. We've been tasked with implementing the fibonacci sequence recursively by forking of child processes for each computation. We're supposed to pass the computed value back up the process chain to the root process (which I figured out he wants us to do with exit statuses). The doPrint argument below is pretty self-explanatory (just print the value), but it's worth mentioning that I always call it with 0 for recursive calls so that the result gets "returned" via exit status instead of getting printed.
I understand how forking works, but the result of my code below is always 1, regardless of the value passed in via command line argument. I've omitted the rest of the code for clarity, but the initial vall is doPrint(arg, 1) where arg is 0 <= x <= 13. If anyone can help me figure out what's wrong (or suggest ways to make it cleaner) then I'd really appreciate it!
I understand how forking works, but the result of my code below is always 1, regardless of the value passed in via command line argument. I've omitted the rest of the code for clarity, but the initial vall is doPrint(arg, 1) where arg is 0 <= x <= 13. If anyone can help me figure out what's wrong (or suggest ways to make it cleaner) then I'd really appreciate it!
static void doFib(int n, int doPrint) { int status; pid_t c_proc; if ((c_proc = fork()) >= 0) { if (c_proc == 0) { if (n == 0) exit(0); else if (n == 1 || n == 2) exit(1); else { int fib; doFib(n - 1, 0); wait(&status); fib = WEXITSTATUS(status); doFib(n - 2, 0); wait(&status); fib += WEXITSTATUS(status); exit(fib); } } else { wait(&status); status = WEXITSTATUS(status); if (doPrint) printf("%d\n", status); else exit(status); } } else { printf("Failed to create process\n"); exit(-1); } }