Last active
October 16, 2015 01:00
-
-
Save codehearts/6e7282984e77b1f5c02e to your computer and use it in GitHub Desktop.
Poking fun at how recursion is taught as the holy grail of CS in entry-level courses.
This file contains 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
/** | |
* Poking fun at how recursion is taught as the holy grail in entry-level CS. | |
* This forks a process for each recursive computation and uses the return | |
* status as the return value. | |
* | |
* Running this might be a really bad idea! | |
*/ | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <stdio.h> | |
int main(int argc, const char *argv[]) { | |
int n = atoi(argv[1]); | |
if (n == 0) { | |
if (argc == 2) { | |
printf("0\n"); | |
} | |
exit(0); | |
} else if (n == 1) { | |
if (argc == 2) { | |
printf("1\n"); | |
} | |
exit(1); | |
} | |
int v1, v2; | |
pid_t p1, p2; | |
char n1[10], n2[10]; | |
if ((p1 = fork()) == 0) { | |
sprintf(n1, "%d", n-1); | |
char *args1[4] = {"a.out", (char *) n1, "noprint", NULL}; | |
execv("a.out", args1); | |
} else if (p1 < 0) { | |
printf("ERROR\n"); | |
} | |
if ((p2 = fork()) == 0) { | |
sprintf(n2, "%d", n-2); | |
char *args2[4] = {"a.out", (char *) n2, "noprint", NULL}; | |
execv("a.out", args2); | |
} else if (p2 < 0) { | |
printf("ERROR\n"); | |
} | |
waitpid(p1, &v1, 0); | |
v1 = WEXITSTATUS(v1); | |
waitpid(p2, &v2, 0); | |
v2 = WEXITSTATUS(v2); | |
if (argc == 2) { | |
printf("%d\n", v1 + v2); | |
} | |
exit(v1 + v2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment