Skip to content

Instantly share code, notes, and snippets.

@zed
Created February 6, 2012 09:36
Show Gist options
  • Select an option

  • Save zed/1751073 to your computer and use it in GitHub Desktop.

Select an option

Save zed/1751073 to your computer and use it in GitHub Desktop.
Recursive Fibonacci using Fork
#!/usr/bin/env python
"""
http://stackoverflow.com/questions/9156823/recursive-fibonacci-using-fork-in-c
"""
import os
import sys
def exitcode(pid):
retpid, status = os.waitpid(pid, 0)
assert retpid == pid and os.WIFEXITED(status)
return os.WEXITSTATUS(status)
def fib(n, doprint=False):
def ret(f):
if doprint:
print(f)
sys.exit()
else:
os._exit(f)
if n < 2: ret(n)
pid = os.fork()
if not pid: fib(n-1) # child 1
pid2 = os.fork()
if not pid2: fib(n-2) # child 2
# parent
ret(exitcode(pid) + exitcode(pid2))
# 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
fib(7, doprint=True) # 7 -> 13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment