title: Recursive Fibonacci in C, using fork()
body: <p>Up front, I readily admit this is homework. But I have been banging my head against the wall on this one and I just don't get it. Assignment parameters are as follows: "Recursively compute the specified number. If print is true, print it. Otherwise, provide it to my parent process. </p>
  
  <p>NOTE: The solution must be recursive and it must fork a new child for each call. Each process should call <code>doFib()</code> exactly once."</p>
  
  <p>This is my first experience using fork(), and though I think I understand, I just cannot wrap my head around why I'm not getting the correct answer. Here is my code, which is fairly rudimentary:</p>
  
  <pre><code>doFib(int n, int doPrint)
  {
      int status;
      int print;
      pid_t pid1;
      pid_t pid2;
      int sum1;
      int sum2;
  
      if (n &lt; 2)
          exit(n);
  
      pid1 = fork();
  
      if (pid1 == 0)
      {
          doFib(n-1, doPrint);
          exit(n-1);
      }
  
      pid2 = fork();
  
      if (pid2 == 0)
      {
          doFib(n-2, doPrint);
          exit(n-2);
      }
  
      while ((pid1 = waitpid(-1,&amp;status, 0)) &gt;0)
      {
          if(WIFEXITED(status))
              sum1 += WEXITSTATUS(status);
      }
  
      while ((pid2 = waitpid(-1,&amp;status, 0)) &gt;0)
      {
          if(WIFEXITED(status))
              sum2 += WEXITSTATUS(status);
      }
  
      print = sum1 + sum2;
  
      if(doPrint)
          printf("%d\n", print);
      else
          exit(0);
  }
  </code></pre>
  
  <p>Fibonacci is one of the first examples of recursion I was taught, and I understand it at a base level. However, when I run my program, with 10 as the given argument (though any argument produces incorrect results), I get a stream of junk ending in: <code>-1861761537</code> (there are lots of these negative numbers), 17. Any changes I make result in different junk values, but still end up at 17.</p>
  
  <p>I believe the problem is in my use of waitpid, but I don't know what it would be. Am I correct in assuming this is the source of my error? I've scoured the textbook, man pages, Internet, etc. and I don't know what I could fix. Any help would be greatly appreciated. Thank you.</p>