Created
February 6, 2012 09:36
-
-
Save zed/1751073 to your computer and use it in GitHub Desktop.
Recursive Fibonacci using Fork
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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