Having fun with fork! Or at least burning some cycles.
Today, we're going back to 1112, and mastering recursion. Remember good 'ol fibonacci:
fib(0) = 0
fib(1) = 1
fib(n) = fib(n - 1) + fib(n - 2)
If it is good enough for the golden ratio, it's good enough for a class exercise!
Implement fib
in C.
I know, real hard.
Use fork
, exit
, and wait
to calculate fib...fibork!
Each recursive "call" to fibork
should be in a new process.
You should not use fib
in your implementation, and each call to fibork
should result in creating two children processes, each of which call fibork
for the recursive call.
You'll have to think about how fork
works to figure out how to pass the argument.
To "return", you'll need to exit
, and to pass the return value, the exit
value will need to percolate to wait
.
Note that when wait(&status)
gets the status from exit
, you must use WEXITSTATUS(status)
to access its value.
You can use man
to figure out how to use these calls appropriately.
Change the optimization settings from -O0
to -O3
, and recompile (make sure to run make clean
).
Form a hypothesis:
- What will happen to the performance of each implementation?
- How much will they improve?
Then execute the system. Does it match your hypothesis? Why or why not?
Remember our old friend, objdump
?
Lets figure out why the performance changed?
Use objdump -S
and look at your function's implementation.
If you want to more easily search through objdump
's output, you might consider outputting to a file (e.g., objdump -S bin > output.txt
).
What made it faster?