-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfib.c
More file actions
112 lines (95 loc) · 1.79 KB
/
fib.c
File metadata and controls
112 lines (95 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
const int MAX = 13;
static void doFib(int n, int doPrint);
pid_t Fork(void);
/*
* unix_error - unix-style error routine.
*/
inline static void
unix_error(char *msg)
{
fprintf(stdout, "%s: %s\n", msg, strerror(errno));
exit(1);
}
int main(int argc, char **argv)
{
int arg;
int print;
if(argc != 2){
fprintf(stderr, "Usage: fib <num>\n");
exit(-1);
}
if(argc >= 3){
print = 1;
}
arg = atoi(argv[1]);
if(arg < 0 || arg > MAX){
fprintf(stderr, "number must be between 0 and %d\n", MAX);
exit(-1);
}
doFib(arg, 1);
return 0;
}
/*
* Recursively compute the specified number. If print is
* true, print it. Otherwise, provide it to my parent process.
*
* NOTE: The solution must be recursive and it must fork
* a new child for each call. Each process should call
* doFib() exactly once.
*/
static void
doFib(int n, int doPrint) /* Zoe and Paul drove in this function */
{
int fib;
// base case
if (n == 0 || n == 1)
{
if (doPrint) fprintf(stdout, "%d\n", n);
exit(n);
}
pid_t pid;
pid_t pid2;
if ((pid = Fork()) == 0)
{
// child
doFib(n - 1, 0);
}
if ((pid2 = Fork()) == 0)
{
// child
doFib(n - 2, 0);
}
if (pid > 0 && pid2 > 0)
{
// parent
int status;
int status2;
waitpid(pid, &status, 0);
waitpid(pid2, &status2, 0);
fib = WEXITSTATUS(status) + WEXITSTATUS(status2);
if (doPrint)
{
fprintf(stdout, "%d\n", fib);
}
exit(fib);
}
}
/* Zoe Drove Here */
/* Taken from Bryant & O'Hall page 718 */
pid_t Fork(void)
{
pid_t pid;
if ((pid = fork()) < 0)
unix_error("Fork error");
return pid;
}
/* done with code excerpt */