0%

MIT 6.S081 lab1

sleep

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "kernel/types.h"
#include "user/user.h"

int main (int n, char *argv[]) {
if(n == 1 || n >= 3) {
printf("Error\n");
exit(1);
}
int num = atoi(argv[1]);
//printf("%d\n",num);
sleep(num);

exit(0);
}

pingpong

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
#include "kernel/types.h"
#include "user/user.h"


int main () {
int p1[2]; // fa -> son (0 read) (1 write)
int p2[2]; // fa <- son
pipe(p1);
pipe(p2);
int pid = fork();
if(pid == 0) {
write(p2[1], "k", 1);
close(p2[0]);
close(p1[1]);
char ch_son[30];
read(p1[0], ch_son, 1);
int son = getpid();
printf("%d: received ping\n", son);
close(p2[1]);
close(p1[0]);
//printf("%c\n", ch_son[0]);
} else {
write(p1[1], "F", 1);
wait(0);
close(p1[0]);
close(p2[1]);
char ch_fa[30];
read(p2[0], ch_fa, 1);
int fa = getpid();
printf("%d: received pong\n", fa);
//printf("%c\n", ch_fa[0]);
close(p1[1]);
close(p2[0]);
}

exit(0);
}

primes

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
#include "kernel/types.h"
#include "user/user.h"

#define N 35
#define READEND 0
#define WRITEEND 1

void child(int *p1);

int main(int argc, char *argv[]) {
int p[2];
pipe(p);
if(fork() == 0) {
child(p);
} else {
close(p[READEND]);
for (int i = 2; i <= N; i++) {
write(p[WRITEEND], &i, sizeof(int));
}
close(p[WRITEEND]);
wait((int*)0);
}

exit(0);
}

void child(int *p1) {
int pr[2];
int n;
close(p1[WRITEEND]);
int read_result = read(p1[READEND], &n, sizeof(int));
if(read_result == 0) {
exit(0);
}
pipe(pr);
if (fork() == 0) {
child(pr);
} else {
close(pr[READEND]);
printf("prime %d\n", n);
int prime = n;
while(read(p1[READEND], &n, sizeof(int)) != 0) {
if(n % prime != 0) {
write(pr[WRITEEND], &n, sizeof(int));
}
}
close(pr[WRITEEND]);
wait((int*)0);
exit(0);
}
}

求大佬赏个饭