-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfib.c
More file actions
110 lines (92 loc) · 2.02 KB
/
fib.c
File metadata and controls
110 lines (92 loc) · 2.02 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
#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);
/*
* 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.
*/
//#Jishen and Terry drove here
static void
doFib(int n, int doPrint)
{
int status_1,status_2;
pid_t pid_1, pid_2;
//base case
if(n == 0){
if(doPrint){
printf("%d\n", 0);
}
exit(0);
}
else if(n == 1 || n==2){
if(doPrint){
printf("%d\n",1);
}
exit(1);
}
//recursive call with child process
else{
//first child process that do doFib(n-1)
pid_1 = fork();
if(pid_1 == 0){
doFib(n-1,0);
}
//secnod child process that do doFib(n-2)
pid_2 = fork();
if(pid_2 ==0)
doFib(n-2, 0);
// parant process that reap all the child process
else if(pid_2 != 0){
waitpid(-1,&status_1,0);
status_1 = WEXITSTATUS(status_1);
//printf("status_1: %d\n", status_1);
waitpid(-1,&status_2,0);
status_2 = WEXITSTATUS(status_2);
//printf("status_2: %d\n", status_2);
if(doPrint == 1){
printf("%d\n", status_1+status_2);
}
exit(status_1+status_2);
}
}
}